Здесь есть несколько вопиющих проблем с вашим подходом.Обязательно прочитайте сначала документацию Flask по обработке сессий, которая дает вам действительно хороший пример для игры:
http://flask.pocoo.org/docs/1.0/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('/')