Django mailbox and send module itsdangerous

Use itsdangerous module

installation

pip install itsdangerous

encryption:

# 导入itsdangerous中要用到的加密类
from itsdangerous import TimedJSONWebSignatureSerializer as TS
# 导入配置文件
from django.conf import settings

# 创建一个itsdangerous模块中加密类的对象,settings.SECRET_KEY为配置文件中的密钥,expires_in为设置过期时间(单位为s)
ts_obj = TS(settings.SECRET_KEY,expires_in=600) # 过期时间600秒

# data为需要被加密的信息
data = {
	'user_id': instance.id,
	'email': instance.email
}

token = ts_obj.dumps(data) # 利用dumps方法进行加密,加密后是bytes类型的数据
token = token.decode() # 将bytes类型数据转换成字符串类型

Decryption:

ts_obj = TS(settings.SECRET_KEY,expires_in=600)

token = token.encode() # 将str转换成bytes

data = ts_obj.loads(token) # token为加密内容,data为解密后的内容

Django Send E-mail

The basic logic:

  • Itsdangerous module using encrypted user information in the link, generating a token
  • Links in messages sent splicing a variable parameter, which is the token
  • Django related method calls to send mail, sending e-mail

configuration settings file

# 固定写法
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# smtp服务器地址
EMAIL_HOST = 'smtp.126.com'
# 固定端口号
EMAIL_PORT = 25
#发送邮件的邮箱
EMAIL_HOST_USER = '[email protected]'
#在邮箱中设置的客户端授权密码
EMAIL_HOST_PASSWORD = 'shanghui123'
#收件人看到的发件人,尖括号中的必须与上面的user一致
EMAIL_FROM = '一刀999<[email protected]>'

In serializers.py write code file to send mail:

from itsdangerous import TimedJSONWebSignatureSerializer as TS
from django.conf import settings
from django.core.mail import send_mail

class EmailSerlizer(serializers.ModelSerializer):
    class Meta:
        model = models.User
        fields = ('id', 'email',)

    def validate(self, attrs):
        return attrs

    def update(self, instance, validated_data):
        '''
        
        :param instance: 视图传递过来的实例对象,通过get_object获取的实例对象
        :param validated_data:
        :return:
        '''
        instance.email = validated_data['email']
        instance.save()
        
        # todo 生成激活链接
        
        # 创建一个itsdangerous模块中加密类的对象,settings.SECRET_KEY为配置文件中的密钥,expires_in为设置过期时间(单位为s)
        ts_obj = TS(settings.SECRET_KEY,expires_in=600) # 过期时间600秒
        data = {
            'user_id': instance.id,
            'email': instance.email
        }
        token = ts_obj.dumps(data) # 利用dumps方法进行加密,加密后是bytes类型的数据
        token = token.decode() # 将bytes类型数据转换成字符串类型
        url = 'http://127.0.0.1:8000/users/varifyemail/?token='+token

        # todo 发送邮件
        
        subject = '新的传奇' # 邮件主题
        message = '点击链接激活邮箱:'+'<a href=' + url + '>点击链接</a>'  # 邮件内容
        sender = settings.EMAIL_FROM # 邮件发送者
        receiver = ['[email protected]',] # 接收邮件的邮箱

        send_mail(subject, message, sender, receiver) # 发送邮件

        return instance

In views.py file code:

from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import UpdateAPIView

class EmailView(UpdateAPIView):
    serializer_class = serializers.EmailSerlizer
    permission_classes = (IsAuthenticated,)

    def get_object(self):
        return self.request.user

In urls.py file code:

urlpatterns = [
    url(r'^email/$', views.EmailView.as_view()),
]

Activate the user's mailbox

The basic logic:

  • After the user receives the message, click on the link, jump to the corresponding view class for processing
  • A view which will decrypt the user's information and the corresponding user query
  • If the user exists, the user will be the corresponding value in the field active_email to True, it indicates that the user mailbox has been activated
  • Returns the successful activation page or activation fails page

In urls.py file code:

Here's a link to the path and fill in when sending mail to the above agreement:

from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^varifyemail/$',views.EmailVarify.as_view()),
]

In views.py file code:

Here we will first decode the token to then be verified by the verification put into a state corresponding to the active state mailbox.

class EmailVarify(APIView):

    def get(self, request):
        # todo 获取网站中的内容
        print('这是一个通过邮箱里面的链接进入的路口', request.query_params.get('token'))
        token = request.query_params.get('token')

        # todo 校验token是否为空
        if not token:
            return Response({'err_msg': '缺少token参数'}, status=400)

        # todo 对token进行解码
        ts_obj = TS(settings.SECRET_KEY)
        token = token.encode()
        data = ts_obj.loads(token)

        # todo 在后端进行校验,判断有没有这个用户
        username = models.User.objects.filter(username=data['username'],email=data['email'])

        if username:
            # todo 修改邮箱是否激活的内容(邮箱状态设为激活)
            username.update(active_email=True)
            return Response('邮箱激活成功')
        else:
            return Response('激活失败')

Guess you like

Origin blog.csdn.net/dakengbi/article/details/92842721