def connect(sid, environ): try: if "HTTP_X_RANDOVANIA_VERSION" not in environ: raise ConnectionRefusedError("unknown client version") client_app_version = environ["HTTP_X_RANDOVANIA_VERSION"] check_client_version(version_checking, client_app_version, server_version) check_client_headers(expected_headers, environ) connected_clients.inc() forwarded_for = environ.get('HTTP_X_FORWARDED_FOR') app.logger.info( f"Client {sid} at {environ['REMOTE_ADDR']} ({forwarded_for}) with " f"version {client_app_version} connected.") except ConnectionRefusedError: # Do not wrap if it's already a ConnectionRefusedError raise except Exception as e: logging.exception( f"Unknown exception when testing the client's headers: {e}") raise ConnectionRefusedError( f"Unable to check if request is valid: {e}.\n" f"Please file a bug report.")
def verify_connection(): session_key = session.get('KEY') if not session_key: raise ConnectionRefusedError('User not logged') key = request.get_json(force=True)['key'] if key != session_key: blocked_sessions.add(session_key) raise ConnectionRefusedError( 'User altered the key. Session is being blocked') elif key not in keys: raise ConnectionRefusedError('Key not registered') if not all([ dict_key in session for dict_key in ['ID', 'ROOM', 'DATETIME', 'NEW', 'TYPE'] ]): blocked_sessions.add(session_key) raise ConnectionRefusedError( 'User altered the session. Session is being blocked') if session['TYPE'] != 'resident' and session['TYPE'] != 'employee': blocked_sessions.add(session_key) raise ConnectionRefusedError( 'User altered the session. Session is being blocked') join_room(session['ROOM'] + '_' + session['TYPE'], request.sid)
def connect(sid, environ): if "HTTP_X_RANDOVANIA_VERSION" not in environ: raise ConnectionRefusedError("unknown client version") client_app_version = environ["HTTP_X_RANDOVANIA_VERSION"] if server_version != client_app_version: raise ConnectionRefusedError( f"Incompatible client version '{client_app_version}', " f"expected '{server_version}'") connected_clients.set(len(sio.get_server().environ)) app.logger.info( f"Client at {environ['REMOTE_ADDR']} with " f"version {client_app_version} connected, while server is {server_version}" )
def on_join(data): if not session["userID"]: return ConnectionRefusedError("Must be logged in to join chat") user = users.getUser(session["userID"]) groupID = data["GROUPID"] if groupID not in user["enrollments"] and groupID not in user[ "mentorships"] and not user["admin"]: return ConnectionRefusedError( "User is not a student or mentor in the requested group") session["user"] = user session["groupID"] = groupID join_room(groupID) send(str("%s has joined the chat." % user["name"]), room=groupID)
def check_client_version(version_checking: ClientVersionCheck, client_version: str, server_version: str): if version_checking == ClientVersionCheck.STRICT: if server_version != client_version: raise ConnectionRefusedError( f"Incompatible client version '{client_version}', " f"expected '{server_version}'") elif version_checking == ClientVersionCheck.MATCH_MAJOR_MINOR: server = StrictVersion(server_version.split(".dev")[0]) client = StrictVersion(client_version.split(".dev")[0]) if server.version[:2] != client.version[:2]: shorter_client = "{}.{}".format(*client.version[:2]) shorter_server = "{}.{}".format(*server.version[:2]) raise ConnectionRefusedError( f"Incompatible client version '{shorter_client}', " f"expected '{shorter_server}'")
def handle_new_connection(): print('Connect', session) if 'username' not in session: print('kashdk') raise ConnectionRefusedError('not authenticated') join_room(session['username'])
def on_join(): token = request.args.get('token') if token: try: decoded_token = decode_token(token) user = User.query.filter_by( email=decoded_token['identity']).first() room = user.device_id if room: join_room(room) print(f'User {user.name} joined {user.device_id}') except Exception: # on any jwt error raise ConnectionRefusedError('unauthorized!') else: raise ConnectionRefusedError('unauthorized!')
def connect(message): userid = __getauthenticateduserid(message) if userid is not None: current_app.logger.info('socket connection established for user: '******' | sid: ' + request.sid) else: disconnect() raise ConnectionRefusedError('unauthorized!')
def connect(): try: systemContoller.connectDrone() print('App connected with ID: ', request.sid, '\n') except DroneConnectionError as error: print(error.getMessage()) raise ConnectionRefusedError('Failed') except IncorrectNetwork as error: print(error.getMessage())
def on_connect(self): username = self.username username = UserManager.find_user_option(username).map(attrgetter('username')).get_or(username) if username: self.session.add_user(username, self.sid) self.enter_room(self.sid, username) else: self.emit('reject', 'You should login first.') raise ConnectionRefusedError('Not Authorized', 'Missing token or token expired.')
def decorated_function(*args, **kwargs): # data = Authentication.validate_jwt(args) # validate access if len(args) > 0: if "token" not in args[0]: raise ConnectionRefusedError("authentication failed") try: print(args[0]) user_name = Authentication.validate_jwt( json.loads(args[0])["token"]) kwargs.update({"username": user_name}) except Exception as ex: raise ConnectionRefusedError("authentication failed") else: raise ConnectionRefusedError("authentication failed") return f(*args, **kwargs)
def on_connect(): token = request.args.get('token') total_credits = int(request.headers.get("Total-Credits")) in_use_credits = int(request.headers.get("In-Use-Credits")) try: probe_data = current_app.token.identity(token) probe = current_app.db.probes.find_probe(probe_data["identifier"]) if probe is None: raise ConnectionRefusedError('Invalid token') conn = Connection(request.sid, total_credits, in_use_credits) current_app.probes[probe] = conn except: # Raising something in except is bad, but we can't do it better for now raise ConnectionRefusedError('Invalid token')
def connect(namespace=None, query_string=None, headers=None): api_key = request.headers.get('token') userId = request.headers.get('userId') if (api_key): token = getToken(userId, api_key) if (token): user = User.verify_auth_token(token) if user: extendToken(user.id) return user raise ConnectionRefusedError('authentication failed')
def handler(): user_id = session.get("user_id") user_username = session.get("user_username") if user_id is None: raise ConnectionRefusedError('unauthorized') session['ws_sid'] = request.sid current_app.logger.debug( f"connect '{request.namespace}', user: '******'")
def connect(): load_player() if g.player is None: raise ConnectionRefusedError() db = get_db() db.execute('UPDATE player SET active = 1' ' WHERE id = ?', (g.player['id'], )) db.commit() print(f"Player '{g.player['username']}' is active.")
def wrapper(*args, **kwargs): # noqa: WPS430 try: verify_jwt_in_request() # `IndexError` is raised when there is empty token sent in # the `Authorization` header, precisely: "Bearer " except (JWTExtendedException, PyJWTError, IndexError): raise ConnectionRefusedError( # this message will be sent on `error` event { 'detail': 'authentication', MESSAGE_KEY: 'Missing or invalid access token', }, ) return event_handler(*args, **kwargs)
def connect(sid, environ): if "HTTP_X_RANDOVANIA_VERSION" not in environ: raise ConnectionRefusedError("unknown client version") client_app_version = environ["HTTP_X_RANDOVANIA_VERSION"] check_client_version(version_checking, client_app_version, server_version) connected_clients.inc() forwarded_for = environ.get('HTTP_X_FORWARDED_FOR') app.logger.info( f"Client at {environ['REMOTE_ADDR']} ({forwarded_for}) with " f"version {client_app_version} connected.")
def on_join(data): data = json.loads(data) session_dict = json.loads( jws.verify(data["session"], getSecretKey(), algorithms=["HS256"])) for key in session_dict: session[key] = session_dict[key] if "userID" not in session: return ConnectionRefusedError("Must be logged in to join chat") user = users.getUser(session["userID"]) groupID = data["GROUPID"] if groupID not in user["enrollments"] and groupID not in user[ "mentorships"] and not user["admin"]: return ConnectionRefusedError( "User is not a student or mentor in the requested group") session["user"] = user session["groupID"] = groupID join_room(groupID) sendSession() send(str("%s has joined the chat." % user["name"]), room=groupID)
def login_handler(data: dict): room_id = data.pop('room_id', 0) password = str(data.pop('password', '')) addr = str(data.pop('addr', '')) if not validate_room_id(room_id): raise ConnectionRefusedError(1, 'Unauthorized') room = Room.query.get(room_id) if room and check_password_hash(room.password, password): user = User(addr=addr, room=room) db.session.add(user) db.session.commit() login_user(user) join_room(room_id) print([u.addr for u in room.users if u.id != user.id]) emit('login', { 'user_id': current_user.id, 'addr_set': [u.addr for u in room.users if u.id != user.id], **data, }, broadcast=False) else: raise ConnectionRefusedError(1, 'Unauthorized')
def connect(): global currentConnections global bebop # Only allow one app to be connected at any given time if currentConnections >= 1: # print('\nToo many apps attempted to connect to drone, kicked', request.sid) # print('Current connections ->', currentConnections, '\n') raise ConnectionRefusedError('Unauthorized!') else: # Establish connection to drone # if bebop.connect_drone(liveStream = False): currentConnections += 1 print('\nApp connected with ID', request.sid) print('Current connections ->', currentConnections, '\n')
def server_connect(): """Sent by clients when they enter a room. A status message is broadcast to all people in the room.""" if self.validate_username(session.get("name")): self.connected_users.append(session.get("name")) emit( "status", { "username": session.get("name"), "msg": "{} has joined.".format(session.get("name")), "connected_users": self.connected_users, "user": session.get("name"), }, broadcast=True, ) else: raise ConnectionRefusedError('You are active from another session!')
def check_client_headers(expected_headers: Dict[str, str], environ: Dict[str, str]): wrong_headers = {} for name, expected in expected_headers.items(): value = environ.get("HTTP_{}".format(name.upper().replace("-", "_"))) if value != expected: wrong_headers[name] = value if wrong_headers: message = "\n".join( f"Expected '{expected_headers[name]}' for '{name}', got '{value}'." for name, value in wrong_headers.items()) raise ConnectionRefusedError( "Incompatible client:\n{}\n\nServer is version {}, please confirm you're updated." .format( message, randovania.VERSION, ))
def connect(): if not current_user.is_authenticated: raise ConnectionRefusedError("User is not logged in, please refresh the page.")
def connect_handler(): if not current_user.is_authenticated: raise ConnectionRefusedError('unauthorized')
def connect(): if not is_logged_in(): raise ConnectionRefusedError('unauthorized!') emit('flash', 'Welcome ') # context aware emit
def connect(): if current_user.is_authenticated: chats = current_user.get_chats() for chat in chats: join_room(chat) else: return ConnectionRefusedError('Unauthorized!')