Flask-Multi-Session provides Mongo session storage for Flask apps. This module allows you to manage user sessions from different devices, thus you can logout user from all devices. Flask-Multi-Session supports python>=3.5.
Install Flask-Multi-Session from pip.
pip3 install flask-multi-session
from flask import Flask, session, redirect, url_for
import random
app = Flask(__name__)
@app.route('/')
def index():
user_id = session.get('user_id')
if user_id is not None:
return """
Hello. This is index page. Your login is %s.<\br>
<a href="/logout">Logout</a> <a href="/logout_all_devices">Logout from all devices</a>
""" % user_id
else:
return 'Hello. This is index page. Please <a href="/login">login</a>.'
@app.route('/login')
def login():
session.login(random.randint(1, 10000))
return redirect(url_for('index'))
@app.route('/logout')
def logout():
session.logout()
return redirect(url_for('index'))
@app.route('/logout_all_devices')
def logout_all_devices():
session.logout_all_devices()
return redirect(url_for('index'))
from flask_multisession import MongoSessionInterface
app.session_interface = MongoSessionInterface()
if __name__ == '__main__':
app.run()
Important! Use "user_id" as a key for unique user id and add one to session after successful login.
Important! Added new method clear_user_sessions to Session class.
Example: session.clear_user_sessions()
delete all sessions for current user, but you can specify user_id: session.clear_user_sessions(user_id=23)
delete all sessions for user with id=23.
If you have a remote Mongo you may specify one in MongoSessionInterface constructor.
mongo_config = dict(
host='192.168.0.1',
port=27017
)
from flask.ext.multisession import MongoSessionInterface
app.session_interface = MongoSessionInterface(**mongo_config)