Skip to content

Commit

Permalink
namespaces: Move hardcoded strigs and values for cosistency
Browse files Browse the repository at this point in the history
Signed-off-by: ZorEl212 <[email protected]>
  • Loading branch information
ZorEl212 committed Sep 14, 2024
1 parent 1da46dc commit 78f2206
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 30 deletions.
21 changes: 21 additions & 0 deletions resources/strings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Strings
# Strings used in the application

# Namespaces - Common
AUTH_FAILED_TIMEOUT = 'Authentication timeout'
AUTH_REQUIRED = 'Authentication required'
AUTH_INVALID_TOKEN = 'Invalid token'
AUTH_MISSING_ID = 'Missing userId or serverId'
AUTH_INVALID_DETAILS = 'Invalid server details'
AUTH_MAX_RETRIES_EXCEEDED = 'Too many attempts, disconnecting...'
DISCONNECTED = 'Disconnected'
CONNECTED = 'Connected'
AUTHENTICATED = 'Authenticated'


# Exceptions
EXC_INVALID_TOKEN = 'Token verification error'
EXC_AUTH_ERROR = 'AuthenticationError'
14 changes: 14 additions & 0 deletions resources/values.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Values

# Namespaces - Common
MAX_RETRIES = 3
AUTH_TIMEOUT = 30

AUTH_ERROR_TIMEOUT = 1005
AUTH_ERROR_INVALID_TOKEN = 1001
AUTH_ERROR_MISSING_ID = 1002
AUTH_ERROR_INVALID_DETAILS = 1003
AUTH_ERROR_MAX_RETRIES = 1004
65 changes: 35 additions & 30 deletions socket_namespaces/common.py
Original file line number Diff line number Diff line change
@@ -1,63 +1,68 @@
from socketio import Namespace
from models import config, sio
from models import sio
from models.auth import Auth
from socketio.exceptions import ConnectionRefusedError
import threading
import resources.strings as strings
import resources.values as values

def auth_timeout(sid, timeout=15):
def auth_timeout(sid, timeout=values.AUTH_TIMEOUT, namespace=None):
def disconnect():
session = sio.get_session(sid, namespace='/daemon')
session = sio.get_session(sid, namespace=namespace)
if not session.get('authenticated', False):
sio.emit('auth_failed', {'message': 'Authentication timeout', 'err_code': 1005}, to=sid, namespace='/daemon')
sio.disconnect(sid, namespace='/daemon')
sio.emit('auth_failed', {'message': strings.AUTH_FAILED_TIMEOUT, 'err_code': values.AUTH_ERROR_TIMEOUT}, to=sid, namespace=namespace)
sio.disconnect(sid, namespace=namespace)
timer = threading.Timer(timeout, disconnect)
timer.start()

class Common(Namespace):
def __init__(self, namespace=None):
super().__init__(namespace)

def on_connect(self, sid, environ, auth):
print(f"Client {sid} connected")
print(f"Client {sid} {strings.CONNECTED}")
if auth is None or 'token' not in auth:
sio.emit('auth_required', {'message': 'Authentication required'}, to=sid, namespace='/daemon')
auth_timeout(sid)
sio.emit('auth_required', {'message': strings.AUTH_REQUIRED}, to=sid, namespace=self.namespace)
auth_timeout(sid, namespace=self.namespace)
return True
try:
payload = Auth.verify_token(auth['token'])
if not payload:
raise ConnectionRefusedError({'message': 'Invalid token', 'err_code': 1001})
raise ConnectionRefusedError({'message': strings.AUTH_INVALID_TOKEN, 'err_code': values.AUTH_ERROR_INVALID_TOKEN})
except Exception as e:
print(f"Token verification error: {e}")
raise ConnectionRefusedError({'message': 'Invalid token', 'err_code': 1001})
session = sio.get_session(sid, namespace='/daemon')
print(f"{strings.EXC_INVALID_TOKEN}: {e}")
raise ConnectionRefusedError({'message': strings.AUTH_INVALID_TOKEN, 'err_code': values.AUTH_ERROR_INVALID_TOKEN})
session = sio.get_session(sid, namespace=self.namespace)
session['authenticated'] = True
sio.save_session(sid, session, namespace='/daemon')
sio.emit('authenticated', {'token': auth['token']}, to=sid, namespace='/daemon')
sio.save_session(sid, session, namespace=self.namespace)
sio.emit('authenticated', {'token': auth['token']}, to=sid, namespace=self.namespace)
return True

def on_authenticate(self, sid, data):
userId = data.get('userId')
serverId = data.get('serverId')

if not userId or not serverId:
sio.emit('auth_failed', {'message': 'Missing userId or serverId', 'err_code': 1002}, to=sid, namespace='/daemon')
print("Missing userId or serverId")
sio.disconnect(sid, namespace='/daemon')
sio.emit('auth_failed', {'message': strings.AUTH_MISSING_ID, 'err_code': values.AUTH_ERROR_MISSING_ID}, to=sid, namespace=self.namespace)
print(strings.AUTH_MISSING_ID)
sio.disconnect(sid, namespace=self.namespace)

retval = Auth.check_server_details(userId, serverId)
if not retval:
sio.emit('auth_failed', {'message': 'Invalid server details', 'err_code': 1003}, to=sid, namespace='/daemon')
sio.emit('auth_failed', {'message': strings.AUTH_INVALID_DETAILS, 'err_code': values.AUTH_ERROR_INVALID_DETAILS}, to=sid, namespace=self.namespace)
print("Invalid server details")
sio.disconnect(sid, namespace='/daemon')
sio.disconnect(sid, namespace=self.namespace)
return

jwe_data = {'userId': userId, 'serverId': serverId}
token = Auth.create_token(jwe_data, sid)
sio.emit('authenticated', {'token': token, 'server': retval}, to=sid, namespace='/daemon')
session = sio.get_session(sid, namespace='/daemon')
sio.emit('authenticated', {'token': token, 'server': retval}, to=sid, namespace=self.namespace)
session = sio.get_session(sid, namespace=self.namespace)
session['authenticated'] = True
sio.save_session(sid, session, namespace='/daemon')
sio.save_session(sid, session, namespace=self.namespace)

def check_auth(self, sid):
session = sio.get_session(sid, namespace='/daemon')
session = sio.get_session(sid, namespace=self.namespace)
return session.get('authenticated', False)

def on_message(self, sid, data):
Expand All @@ -68,16 +73,16 @@ def on_message(self, sid, data):
print(f"Received message from {sid}: {data}")

def handle_unauthorized(self, sid):
session = sio.get_session(sid, namespace='/daemon')
session = sio.get_session(sid, namespace=self.namespace)
session['message_count'] = session.get('message_count', 0) + 1
sio.save_session(sid, session, namespace='/daemon')
sio.save_session(sid, session, namespace=self.namespace)

if not self.check_auth(sid):
if session['message_count'] >= 3:
sio.emit('auth_failed', {'message': 'Too many attempts, disconnecting...', 'err_code': 1004}, to=sid, namespace='/daemon')
sio.disconnect(sid, namespace='/daemon')
if session['message_count'] >= values.MAX_RETRIES:
sio.emit('auth_failed', {'message': strings.AUTH_MAX_RETRIES_EXCEEDED, 'err_code': values.AUTH_ERROR_MAX_RETRIES}, to=sid, namespace=self.namespace)
sio.disconnect(sid, namespace=self.namespace)
else:
sio.emit('auth_required', {'message': 'Authentication required'}, to=sid, namespace='/daemon')
sio.emit('auth_required', {'message': strings.AUTH_REQUIRED}, to=sid, namespace=self.namespace)

def on_disconnect(self, sid):
print(f"Client {sid} disconnected")
print(f"Client {sid} {strings.DISCONNECTED}")

0 comments on commit 78f2206

Please sign in to comment.