Search code examples
pythonflaskitsdangerous

problem in setting expire time for email conformation in flask


i have this code for email confirm in my flask app but max_age dosent and always even i wait 2 hours its work i use this articel for writing this cod https://realpython.com/handling-email-confirmation-in-flask/ what is this cod problem and how can i fix this

from itsdangerous import URLSafeSerializer
from flask_mail import Mail, Message

mail = Mail(flask_app)
serializer = URLSafeSerializer(flask_app.secret_key)


@flask_app.route("/confirm", methods=["POST", "GET"])
@login_required
def confirm():
    image = get_photo("cafe")
    user_email = current_user.email
    message = "Please Confirm your Email address with the link blow"
    token = serializer.dumps(user_email, salt="email-confirm")
    link = url_for("confirm_email", token=token, _external=True)
    unsubscribe_token = serializer.dumps(user_email, salt="unsubscribe")
    unsubscribe = url_for("unsubscribe", _external=True, token=unsubscribe_token)

    msg = Message("Confirm Email",
                  sender=flask_app.config["MAIL_USERNAME"],
                  recipients=[user_email])

    msg.body = render_template("public/email/single-news.html",
                               user=current_user,
                               link=link,
                               image=image,
                               message=message,
                               unsubscribe=unsubscribe)

    msg.html = render_template("public/email/single-news.html",
                               user=current_user,
                               link=link,
                               image=image,
                               message=message,
                               unsubscribe=unsubscribe)

    mail.send(msg)

    return redirect(url_for("index"))

@flask_app.route("/confirm_email/<token>")
def confirm_email(token):
    try:
        email = serializer.loads(token, salt="email-confirm", max_age=10)
    except Exception as e:
        print(e.args[0])
        abort(406)
    else:
        return render_template("public/confirm.html",
                               user=current_user,
                               title="confirimed")

Solution

  • after reading some more docs i found the problem and i post the answer here maybe help the others i must user URLSafeTimedSerializer and TimestampSigner not URLSafeSerializer so i change the import to

    from itsdangerous import URLSafeTimedSerializer, TimestampSigner
    from flask_mail import Mail, Message
    

    and use them :

    serializer = URLSafeTimedSerializer(flask_app.config["SECRET_KEY"])
    timestamp = TimestampSigner(flask_app.config["SECRET_KEY"])
    

    now its work fine