socket: Reduce code duplication in authentication error cases

(imported from commit e7900b1374c3c0e5ea994ff315d281833e7ecdc6)
This commit is contained in:
Zev Benjamin 2013-11-04 16:25:56 -05:00
parent e0fece4082
commit 63924ea742
1 changed files with 12 additions and 11 deletions

View File

@ -65,6 +65,10 @@ def fake_log_line(conn_info, time, ret_code, path, email):
(conn_info.ip, 'SOCKET', ret_code, format_timedelta(time), (conn_info.ip, 'SOCKET', ret_code, format_timedelta(time),
path, email)) path, email))
class SocketAuthError(Exception):
def __init__(self, msg):
self.msg = msg
class SocketConnection(sockjs.tornado.SockJSConnection): class SocketConnection(sockjs.tornado.SockJSConnection):
def on_open(self, info): def on_open(self, info):
self.authenticated = False self.authenticated = False
@ -86,19 +90,11 @@ class SocketConnection(sockjs.tornado.SockJSConnection):
user_profile = get_user_profile(self.browser_session_id) user_profile = get_user_profile(self.browser_session_id)
if user_profile is None: if user_profile is None:
error_msg = 'Unknown or missing session' raise SocketAuthError('Unknown or missing session')
fake_log_line(self.session.conn_info, 0, 403, error_msg, 'unknown')
self.session.send_message({'client_meta': msg['client_meta'],
'response': {'result': 'error', 'msg': error_msg}})
return
self.session.user_profile = user_profile self.session.user_profile = user_profile
if msg['request']['csrf_token'] != self.csrf_token: if msg['request']['csrf_token'] != self.csrf_token:
error_msg = 'CSRF token does not match that in cookie' raise SocketAuthError('CSRF token does not match that in cookie')
fake_log_line(self.session.conn_info, 0, 403, error_msg, 'unknown')
self.session.send_message({'client_meta': msg['client_meta'],
'response': {'result': 'error', 'msg': error_msg}})
return
self.session.send_message({'client_meta': msg['client_meta'], self.session.send_message({'client_meta': msg['client_meta'],
'response': {'result': 'success', 'msg': ''}}) 'response': {'result': 'success', 'msg': ''}})
@ -113,7 +109,12 @@ class SocketConnection(sockjs.tornado.SockJSConnection):
msg = ujson.loads(msg) msg = ujson.loads(msg)
if msg['type'] == 'auth': if msg['type'] == 'auth':
self.authenticate_client(msg) try:
self.authenticate_client(msg)
except SocketAuthError as e:
fake_log_line(self.session.conn_info, 0, 403, e.msg, 'unknown')
self.session.send_message({'client_meta': msg['client_meta'],
'response': {'result': 'error', 'msg': e.msg}})
return return
else: else:
if not self.authenticated: if not self.authenticated: