1
votes

In my Flask-SQLAlchemy web application I have implemented Flask-Login for user authentication and authorization. Now I am building an Admin section where the admin user can add, edit or delete any user and view user list. So before deleting any user I want to know whether that user is currently logged in to the application from somewhere or simply having any active session with the web application. How can I accomplice this? Or Is this even possible in the application level?

[Note: As you can see, this is NOT about current_user.is_authenticated]

1
You need to use socket to know the list of users is currently logged in.ASSILI Taher
Another possible solution: Add is_login to user table. when user log in, is_login=true and when user is log out, is_login=false. But this solution has some disadvantages. For example, when the user log in then close the browser without log out.ASSILI Taher
Yes I thought about that. But there is no way to tap session expired event in flask as per my knowledge. That's a problem.Tamonash Gupta

1 Answers

1
votes

You will have to implement this feature yourself as there is not a way to do it natively with flask-login.

I can think of myriad ways to do this, but the quickest is probably just keeping track of the last time a user accessed your site. Then you can set a reasonable timeout where you assume the user is not logged in if they haven't done anything for the last 30 minutes (or however long you feel comfortable with)

For example:

@app.before_request
def update_last_active():
    current_user.last_active = datetime.utcnow()
    db.session.commit()

This would update User.last_active every time the user sends a request to your server.