2020-12-17 13:39:29 +00:00
|
|
|
import json
|
|
|
|
|
|
|
|
import tornado.websocket
|
|
|
|
from app.classes.shared.console import console
|
2021-03-01 00:54:20 +00:00
|
|
|
from app.classes.shared.models import Users, db_helper
|
2021-02-26 15:39:35 +00:00
|
|
|
from app.classes.web.websocket_helper import websocket_helper
|
2020-12-17 13:39:29 +00:00
|
|
|
|
|
|
|
|
2021-03-01 00:54:20 +00:00
|
|
|
class SocketHandler(tornado.websocket.WebSocketHandler):
|
|
|
|
|
|
|
|
def get_remote_ip(self):
|
|
|
|
remote_ip = self.request.headers.get("X-Real-IP") or \
|
|
|
|
self.request.headers.get("X-Forwarded-For") or \
|
|
|
|
self.request.remote_ip
|
|
|
|
return remote_ip
|
|
|
|
|
|
|
|
def check_auth(self):
|
|
|
|
user_data_cookie_raw = self.get_secure_cookie('user_data')
|
|
|
|
|
|
|
|
if user_data_cookie_raw and user_data_cookie_raw.decode('utf-8'):
|
|
|
|
user_data_cookie = user_data_cookie_raw.decode('utf-8')
|
|
|
|
user_id = json.loads(user_data_cookie)['user_id']
|
|
|
|
query = Users.select().where(Users.user_id == user_id)
|
|
|
|
if query.exists():
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2020-12-17 13:39:29 +00:00
|
|
|
|
|
|
|
def open(self):
|
2021-03-01 00:54:20 +00:00
|
|
|
if self.check_auth():
|
|
|
|
self.handle()
|
|
|
|
else:
|
|
|
|
websocket_helper.send_message(self, 'notification', 'Not authenticated for WebSocket connection')
|
|
|
|
self.close()
|
|
|
|
db_helper.add_to_audit_log_raw('unknown', 0, 0, 'Someone tried to connect via WebSocket without proper authentication', self.get_remote_ip())
|
|
|
|
websocket_helper.broadcast('notification', 'Someone tried to connect via WebSocket without proper authentication')
|
|
|
|
|
|
|
|
def handle(self):
|
|
|
|
|
2021-02-26 15:39:35 +00:00
|
|
|
websocket_helper.addClient(self)
|
2020-12-17 13:39:29 +00:00
|
|
|
console.debug('Opened WebSocket connection')
|
2021-03-01 00:54:20 +00:00
|
|
|
# websocket_helper.broadcast('notification', 'New client connected')
|
2020-12-17 13:39:29 +00:00
|
|
|
|
2021-01-18 19:34:29 +00:00
|
|
|
def on_message(self, rawMessage):
|
2020-12-17 13:39:29 +00:00
|
|
|
|
2021-01-18 19:34:29 +00:00
|
|
|
console.debug('Got message from WebSocket connection {}'.format(rawMessage))
|
|
|
|
message = json.loads(rawMessage)
|
2021-02-27 12:05:04 +00:00
|
|
|
console.debug('Event Type: {}, Data: {}'.format(message['event'], message['data']))
|
2020-12-17 13:39:29 +00:00
|
|
|
|
|
|
|
def on_close(self):
|
2021-02-26 15:39:35 +00:00
|
|
|
websocket_helper.removeClient(self)
|
2020-12-17 13:39:29 +00:00
|
|
|
console.debug('Closed WebSocket connection')
|
2021-03-01 00:54:20 +00:00
|
|
|
# websocket_helper.broadcast('notification', 'Client disconnected')
|
2020-12-17 13:39:29 +00:00
|
|
|
|