From 6429392a405c2812a04ad4c7653d885e7595e255 Mon Sep 17 00:00:00 2001 From: Saptak S Date: Sun, 14 Nov 2021 23:28:17 +0530 Subject: [PATCH] Adds username validation for socketio event handler as well --- .../resources/static/js/chat.js | 2 + cli/onionshare_cli/web/chat_mode.py | 44 +++++++++++-------- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/cli/onionshare_cli/resources/static/js/chat.js b/cli/onionshare_cli/resources/static/js/chat.js index 2be55488..5f290be8 100644 --- a/cli/onionshare_cli/resources/static/js/chat.js +++ b/cli/onionshare_cli/resources/static/js/chat.js @@ -93,6 +93,8 @@ var updateUsername = function (socket) { console.log(response); if (response.success && response.username == username) { socket.emit('update_username', { username: username }); + } else { + addStatusMessage("Failed to updated username.") } }); return username; diff --git a/cli/onionshare_cli/web/chat_mode.py b/cli/onionshare_cli/web/chat_mode.py index 5f2e30f5..7965b722 100644 --- a/cli/onionshare_cli/web/chat_mode.py +++ b/cli/onionshare_cli/web/chat_mode.py @@ -47,6 +47,13 @@ class ChatModeWeb: self.define_routes() + def validate_username(self, username): + return ( + username + and username not in self.connected_users + and len(username) < 128 + ) + def define_routes(self): """ The web app routes for chatting @@ -78,11 +85,7 @@ class ChatModeWeb: def update_session_username(): history_id = self.cur_history_id data = request.get_json() - if ( - data.get("username", "") - and data.get("username", "") not in self.connected_users - and len(data.get("username", "")) < 128 - ): + if self.validate_username(data.get("username", "")): session["name"] = data.get("username", session.get("name")) self.web.add_request( request.path, @@ -141,23 +144,28 @@ class ChatModeWeb: """Sent by a client when the user updates their username. The message is sent to all people in the server.""" current_name = session.get("name") - if message.get("username", ""): + if self.validate_username(message.get("username", "")): session["name"] = message["username"] self.connected_users[ self.connected_users.index(current_name) ] = session.get("name") - emit( - "status", - { - "msg": "{} has updated their username to: {}".format( - current_name, session.get("name") - ), - "connected_users": self.connected_users, - "old_name": current_name, - "new_name": session.get("name"), - }, - broadcast=True, - ) + emit( + "status", + { + "msg": "{} has updated their username to: {}".format( + current_name, session.get("name") + ), + "connected_users": self.connected_users, + "old_name": current_name, + "new_name": session.get("name"), + }, + broadcast=True, + ) + else: + emit( + "status", + {"msg": "Failed to update username."}, + ) @self.web.socketio.on("disconnect", namespace="/chat") def disconnect():