using flask auth.verify_password with session

375 Views Asked by At

I'm struggling a bit to get the auth working properly. I'm controlling the login behavior through api's instead of the web application. For this, i'm using flask session and HTTPBasicAuth(). After a user logs in and until he logs out, I don't want him to re-login (or) post auth for every request to the api. For this i'm leveraging session['username'].

My code for auth.verify_password is below.

    @auth.verify_password
    def verify_password(username, password):
        if 'username' in session:
            return True
        else:
            where_col = "username"
            if '@' in parseaddr('username')[1]:
                where_col = "email"

            conn = mysql.connect()
            cur = conn.cursor()
            sql = "SELECT email, pwd FROM users_table WHERE {}=%s".format(where_col)
            cur.execute(sql, (username))
            row = cur.fetchone()
            cur.close()
            conn.close()
            if not row:
                print "Invalid user"
                return False
            session['username'] = username
            return check_password_hash(row[1], password)

Now, after the login is complete, I want to get some other product data for which I will check using the `auth.login_required` decorator

@app.route('/products', methods=['GET', 'POST'])
@auth.login_requied
def get_products():
    conn = mysql.connect()
    cur = conn.cursor()
    sql = "select * from all_products"
    row = cur.fetchall()
    cur.close()
    conn.close()
    return row

@app.route('/logout', methods=['GET', 'POST'])
@auth.login_requied
def logout():
    session.pop(auth.username())

Next time when I call get_products, I don't want to pass auth to the request header. The above code is not working when I do that. I feel some very little code is missing somewhere (or) that my approach is completely wrong. The session['username'] doesn't seem to persist. It has to go through the login approach everytime, whereas my goal is to skip login until a user logs out. Appreciate any suggestions here.

0

There are 0 best solutions below