flask-邮箱验证链接

大致思路:
1.点击一个验证按钮后,像邮箱发送一封信。
2.用户点击信封的链接后,跳转到一个页面,可以是忘记密码的页面,也可以是其他页面。


给用户发送的链接需要是独一无二的


1.生成email密文:

# 生成email密文,
def generate_confirmation_token(email):
    serializer = URLSafeTimedSerializer(app.config["SECRET_KEY"])
    return serializer.dumps(email, app.config["SECURITY_PASSWORD_SALT"])

2.确认email密文:

# 确认email密文
def confirm_token(token, expiration=3600):
    serializer = URLSafeTimedSerializer(app.config["SECRET_KEY"])
    try:
        email = serializer.loads(
            token,
            salt=app.config['SECURITY_PASSWORD_SALT'],
            max_age=expiration
        )
    except:
        return False
    return email

2.点击按钮,发送一封邮箱


邮箱的配置可以看邮箱的配置

# 发送邮箱
@app.route('/send_email')
def send_email():
    # 再数据库中记录当前发送时间
    title = "hello"
    print(current_user.email_send_time)
    # 目前时间 - 数据库中邮箱发送的时间 的 秒数
    time_delta = (datetime.now() - current_user.email_send_time).total_seconds()
    # 超过60秒,说明邮箱间隔有一分钟,发送邮件
    if time_delta > 60:
        # 更新用户的数据库的邮箱发送时间
        current_user.email_send_time = datetime.now()
        current_user.save()
        # 获取目前用户的email
        email = current_user.email
        # 设置邮箱的信息,发送方,接受方
        msg = Message(title, sender=app.config["MAIL_USERNAME"], recipients=[email])
        # 生成邮箱密文
        email_token = generate_confirmation_token(email)
        # 构造email链接
        email_link = "http://0.0.0.0:1234/confirm/" + email_token
        # 邮箱的html主体内容
        email_html = render_template('email/xxxx.html', email_link=email_link)
        msg.html = email_html
        # 发送邮箱
        mail.send(msg)
        flash("发送成功", "send_email")
        print("发送成功")
    else:
        flash("你已经发送过一封邮箱啦!等待60秒", 'send_email')
        print("你已经发送过一封邮箱啦!等待60秒")
    return redirect(url_for('xxx.xxx'))

3.用户邮箱中的链接


# 接受邮箱
@app.route('/confirm/<token>')
def confirm_email(token):
    # 解密,确认邮箱
    try:
        email = confirm_token(token)
    except:
        flash('xxxx.')
    if email:
        user = User.objects.get_or_404(email=email)
        # 如果邮箱未被验证
        if user.email == email:
            if not current_user.email_is_validation:
                user.email_is_validation = True
                user.save()
            else:
                pass
    else:
        pass
    return render_template('xxx.html')

猜你喜欢

转载自blog.csdn.net/weixin_34025051/article/details/88199501