python-3.xflaskgoogle-app-engineflask-logingoogle-app-engine-python

Flask-login users are being logged out at random when app is live (not when run local)


I have a Flask app, with user Authentication. Its working fine when run in a venv but as soon as i deploy it as a google cloud app it starts logging users out at random, sometimes it can be minutes and other times it at one of the first requests.

Here are the most central parts of my app, I beleive the error must be here or in the App Engine configuration.

db=SQLAlchemy()


def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = os.urandom(12)
    app.config['SQLALCHEMY_DATABASE_URI'] = "my_db_uri"
    db.init_app(app)

    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')

    from .models import User

    login_manager = LoginManager(app)
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)


    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    return app

app = create_app()

if __name__ == '__main__':
    app.run(debug=True)



Solution

  • I was using os.urandom() to generate a random secret key in a settings file.

    The problem was solved when I changed it to a string.

    I guess the problem was that App Engine is running several instances and got differend secret keys from time to time, which made the session cookie invalid and therefor cleared the cookie content.