Flask-Login - User returns to Anonymous after successful login then redirect
<p>I'm trying just to setup a base login model with developed code mostly from <a href="https://flask-login.readthedocs.io/en/latest/" rel="nofollow" title="Flask-Login">Flask-Login</a>.  </p>

<p>After my user successfully logs in and I issue a <code>redirect(url_for('index'))</code>, the user loses his authentication and returns to the value <code>flask_login.AnonymousUserMixin.</code></p>

<p>I realize there are some simple workarounds but I'm trying to understand why my code doesn't work like the examples.</p>

<p>I must be missing something simple or a lack understanding of Flask-Login. How can the user remain logged in after a redirect?</p>

<pre><code>__init__.py
...
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
...
models.py
class User(UserMixin, db.Model):
    __tablename__ = 'users'
    uid = db.Column(db.Integer, primary_key=True)
    firstname = db.Column(db.String(100))
    lastname = db.Column(db.String(100))
    username = db.Column(db.String(100), unique=True)
    email = db.Column(db.String(120), unique=True)
    pwdhash = db.Column(db.String(54))

    def __init__(self, firstname, lastname, email, username, password):
    ... self ... = ....
    def get_id(self):
        return(self.username)
    def __repr__(self):
        return '&lt;User is:%r&gt;' % (self.username)        
routes.py
@login_manager.user_loader
def load_user(user_id):
    try:
        return User.query.get(user_id)
    except:
        return None

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if request.method == "POST":
        if form.validate():
            user = User.query.filter_by(username=form.username.data.lower()).first()
            login_user(user, remember=False)
            assert current_user.is_authenticated
            return redirect(url_for('index'))
        else:
            return render_template('login.html', form=form)
    return render_template('login.html', form=form)

@app.route('/index')
@login_required
def index():
    return render_template("home.html")
</code></pre>

<p>I have reviewed <a href="http://stackoverflow.com/questions/30150626/flask-login-user-is-set-to-anonymous-after-login" title="flask-login user is set to anonymous after login">flask-login user is set to anonymous after login</a> but that login method is different than the one above.</p>

<p>Well, I need to answer my own question on a dumb oversight that I should have caught (bleary eyes?)</p>

<p>Simple fix in <code>def load_user(user_id):</code> where I needed to replace the line<br></p>

<p>Bad: <code>return User.query.get(user_id)</code></p>

<p>Good: <code>return User.query.filter_by(username=user_id).first()</code></p>

<p>I suppose the take-away is the importance of <code>def load_user()</code> in preserving session integrity.</p>

python flask-login