[FIXED] How can I keep user into the session

Issue

user=users.query.filter(db.and_(users.username ==  request.form['username'] ,users.password==request.form['password'])).first()

I’ve already tried

app.config['user'] = user and session['user']=user

,but it doesn’t work

Solution

There are a few glaring issues with your approach here. Be sure to read Flask documentation on handling sessions first, which gives you a really nice example to play with:

http://flask.pocoo.org/quickstart/#sessions

from flask import Flask, session, redirect, url_for, escape, request
from werkzeug.security import check_password_hash

app = Flask(__name__)

app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

def get_session_user():
    if 'username' not in session:
        return None
    username = session['username']
    # fetch the user from database somehow
    user = db.get_user_by_username(username)
    return user

def verify_password(hashed: str, password: str) -> bool:
    return check_password_hash(hashed, password)

@app.route('/')
def index():
    user = get_session_user()
    if user:
        return f'You are logged in as {user.username}'
    return f'Please <a href="/login">login</a>'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = db.get_user_by_username(username)
        
        if not user:
            return 'No such user'
        
        # hopefully you're storing hashed passwords in DB
        # you need to check if the credentials matches what's stored in DB
        if not verify_password(user.hashed_password, password):
            return 'Invalid credentials'
        
        session['username'] = user.username
        return redirect('/')
    
    return '''
        <form method="post">
            <input name='username' placeholder='username'>
            <input type='password' name='password' placeholder='password'>
            <button>Login</button>
        </form>
    '''

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect('/')

Answered By – abdusco

Answer Checked By – Marie Seifert (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published