如何使用JSON Web令牌在Flask中实现两因素身份验证?

时间:2020-05-30 15:01:17

标签: flask jwt

我想通过在用户登录后使用gmail向用户发送包含jwt的url来实现2因子身份验证。包含令牌的链接被邮寄给用户,该用户单击后会将用户重定向到仪表板。我正在使用mysql连接器作为数据库。这是我的代码:

app.secret_key=os.urandom(24)
@app.route('/admin_login')
def admin_login():
    if ('admin_id' in session):
        return redirect('admin_dashboard')
    else :
        return render_template('admin_login.html')


def mail(token, email):
    port = 465  # For SSL
    smtp_server = "smtp.gmail.com"
    sender_email = "mihirsharma999@gmail.com"  # Enter your address
    receiver_email = email# Enter receiver address
    token=token
    t=jwt.decode(token, app.secret_key)
    password = 'eminem@eminem'
    message = """\
    MIME-Version: 1.0
    Content-type: text/html
    Subject: verify token

    <b>{}</b>

    """.format(url_for('verify') + "?token=" +str(token))


    context = ssl.create_default_context()
    with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message)




def generate_token(email, userid):
    # cursor.execute("SELECT admin_id FROM admin WHERE admin_email={}".format(email))

    # aisa use krr k userid nikal
    user = { "userid" : userid }
    token = jwt.encode(user, app.secret_key)
    mail(token, email)
    print("http://127.0.0.1:5000/verify?token=" + str(token) )



@app.route('/verify')
def verify():

    token = request.args.get("token")
    if token:
        try:
            user = jwt.decode(token, app.secret_key)
            userid = user['userid']
            session['admin_id'] = userid
            return redirect('/admin_dashboard')

            # Idhar verify krne ka code likh de.
            # Jo bhi sql query hai wagere, fir redirect to homepage
        except Exception as e:
            flash("token is invalid")

            return redirect('/admin_login')
            print(e)
            pass
            # Idhar aaya iska matlab token invalid hai. To login page pe redirect krr de
    else:
        flash("token missing")
        return redirect('/admin_login')
        # Idhar aaya matlab token hi nai hai. To login page pe redirect krr de
        pass

@app.route('/alogin_validation' ,methods=['POST'])
def alogin_validation():
    email=request.form.get('email')
    password=request.form.get('password')

    try:
        cursor.execute("SELECT * FROM admin WHERE admin_email ='{}' and admin_password ='{}'".format(email,password))
        admins = cursor.fetchall()
        if len(admins) > 0:
            userid =admins[0][0]
            generate_token(email, userid)
            return "<h1>We Have Sent Email</h1>"
        else :
            flash("Incorrect email or password !!")
            return  redirect('/admin_login')
    except mysql.connector.Error as err:
        print(err)
        return redirect('/admin_login')

有人可以告诉我该代码中要进行哪些更改吗?我遇到了很多错误。

0 个答案:

没有答案