Flask:2FA if 语句可能由于不同的变量类型而不断失败?

Flask: 2FA if statement keeps failing potentially due to different vaiable types?

我尝试使用 flask-email 创建自己的 2FA 代码 我在这里生成一个 6 位数的 OTP:

def OTP(length):
    printable = '0123456789'
    printable = list(printable)
    random.shuffle(printable)
    OTP = random.choices(printable, k=length)
    OTP = ''.join(OTP)
    return OTP

然后我在此处发送一封包含 OTP 的电子邮件和 return OTP,以便我稍后使用

def email():
    email = session['email']
    password = OTP(6)
    msg = Message('Business Account 2FA Password', sender='sholto@nea.com', recipients=[email])
    msg.body = ('Hi ' + email + ' Please use this OTP (one time password) to access your business account: \n' + password)
    mail.send(msg)
    return password

这里我使用 OTP = email() 发送电子邮件并获取密码值,然后代码检查用户输入的 OTP 是否与 OTP 变量中存储的匹配。

@app.route('/Authentication', methods = ['POST','GET'])
def Authentication():
    OTP = email()
    if request.method=='POST':
        pass1=request.form.get('password1')
        if pass1==OTP:
            flash('business account login successful')
            session['compcode']=compcode
            session['uniquepass']=uniquepass
            return redirect(url_for('user'))
        else:
            flash('Incorrect Password')
            return redirect(url_for('logout'))
    return render_template('2FA.html')

无论我输入 OTP 多少次并输入正确的 OTP,if 语句总是落入 else 子句。 grrr 请帮助 p.s(我认为问题可能是我正在比较两种不同的数据类型但是在尝试操作变量之后我仍然丢失了!) HTML 模板代码如下

{%extends 'base.html'%}
{%block title%}2FA{%endblock%}
{%block content%}
{% with messages = get_flashed_messages() %}
        {% if messages %}
            {% for msg in messages %}
                <p style="color:red;">{{msg}}</p>
            {%endfor%}
        {%endif%}
{%endwith%}
<p>Please enter the OTP sent to your email below</p>
<form method="post">
    <p><input type="number" name="password1" placeholder="Enter OTP"></p>
    <p><input type="submit" value="submit"></p>
</form>
{%endblock%}

这里的问题是您每次都生成一个新的 OTP,即使您正在检查前一个 OTP。所以他们永远不会匹配。

您可以尝试在会话中设置 OTP 并检查它。类似于:

@app.route('/Authentication', methods = ['POST','GET'])
def Authentication():
    if request.method=='GET':
        OTP = email()
        session['OTP'] = OTP
        return render_template('2FA.html')
    elif request.method=='POST':
        pass1=request.form.get('password1')
        OTP = session.pop('OTP')
        if pass1==OTP:
            flash('business account login successful')
            session['compcode']=compcode
            session['uniquepass']=uniquepass
            return redirect(url_for('user'))
        else:
            flash('Incorrect Password')
            return redirect(url_for('logout'))

在上面,请求的 GET 版本将发送带有 OTP 的电子邮件,将 OTP 存储在会话中,并呈现模板。 POST 版本将从会话中获取 OTP 并从表单中获取代码并检查它们是否匹配。