60 lines
1.8 KiB
Python
60 lines
1.8 KiB
Python
import logging
|
|
import threading
|
|
|
|
from flask_jwt_extended import verify_jwt_in_request, get_current_user, jwt_required, get_jwt_claims, get_jwt_identity
|
|
from flask_login import current_user
|
|
from flask_socketio import SocketIO, emit
|
|
|
|
from backend import app
|
|
|
|
logger = logging.getLogger("lrc.websocket")
|
|
|
|
async_mode = 'threading' # set to traditional python threading model
|
|
# async_mode = None
|
|
socketio = SocketIO(app, cors_allowed_origins="*", async_mode=async_mode)
|
|
|
|
|
|
class WebSocketBase:
|
|
def __init__(self, flask_app_context=None):
|
|
if flask_app_context is None:
|
|
self.flask_app_context = app
|
|
self.socket_thread = None
|
|
|
|
def start_websocket_in_thread(self, host=None, port=None, debug=None):
|
|
self.socket_thread = threading.Thread(
|
|
target=self.start_websocket,
|
|
args=(host, port, debug))
|
|
self.socket_thread.start()
|
|
return self.socket_thread
|
|
|
|
def start_websocket(self, host=None, port=None, debug=None):
|
|
if debug is None:
|
|
debug = self.flask_app_context.debug
|
|
socketio.run(self.flask_app_context, host=host, port=port, debug=debug)
|
|
|
|
@staticmethod
|
|
@socketio.on('connect')
|
|
def connect_handler():
|
|
logger.debug("new connection...")
|
|
try:
|
|
print(verify_jwt_in_request())
|
|
print(get_jwt_identity())
|
|
except:
|
|
logger.info("user is not authenticated!")
|
|
print("not allowed!!")
|
|
return False # not allowed here
|
|
logger.debug("user is authenticated")
|
|
print("allowed!")
|
|
return True
|
|
|
|
@socketio.on_error()
|
|
def handle_error(self, error):
|
|
logger.error(error)
|
|
print(error)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
wsb = WebSocketBase()
|
|
# wsb.start_websocket_in_thread(debug=True)
|
|
wsb.start_websocket(debug=True)
|