后端
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.authentication import jwt_decode_handler
from rest_framework_jwt.utils import jwt_decode_handler
from userapp.ser import *
import jwt
#自己封装的 加密token
from utls.create_token import create_token
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import redis
my_sender = '@qq.com' # 发件人邮箱账号
my_pass = '' # 发件人邮箱的授权码
my_user = '@qq.com' # 收件人邮箱账号,我这边发送给自己
class ZhaohuiView(APIView):
def post(self,request):
#前端要修改的用户名 和 邮箱
username = request.data.get('username')
emial = request.data.get('emial')
if username:
#查找
user = User.objects.get(username=username)
#把这个用户信息 token 加密
token = create_token(user)
#讲url 拼接 发送道邮箱 邮箱里面点击 url 跳转到 vue页面
url = 'http://localhost:8080/emial?'+'token=' +token
msg = MIMEText('修改密码链接:{0}'.format(url), 'plain', 'utf-8')
msg['From'] = formataddr(["From nicead.top", my_sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
msg['To'] = formataddr(["FK", my_user]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号
msg['Subject'] = "验证码" # 邮件的主题,也可以说是标题
server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 发件人邮箱中的SMTP服务器,端口是25
server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号、邮箱密码
server.sendmail(my_sender, [my_user, ], msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
server.quit() # 关闭连接
return Response({'code':200,'msg':'发送成功'})
else:
return Response({"code":400,'msg':'参数不完整'})
def put(self,request):
#前端发送的数据
token= request.data.get('token')
password = request.data.get('password')
#解析jew 拿到 user_id
uid = jwt_decode_handler(token)['user_id']
#根据id查具体用户
user = User.objects.filter(id=uid).first()
user.password = password
user.save()
return Response({'code':200,'msg':'修改成功'})
自己utls里封装的create_token
from rest_framework_jwt.settings import api_settings
def create_token(user):
# 生成jwt-token user 对象 , 查询 结果
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
return token
vue
1.首先写个页面把用户名 邮箱发送道后端
2. 点击发送 后端拼接url发送到邮箱 在邮箱里跳转到vue页面
3. 跳转到的页面token:this.$route.query.token获取token 和 密码 发送到后端 后端解析token
4. uid = jwt_decode_handler(token)['user_id'] #解析出来是一个对象