def secure(self): # use django middleware to get session and authenticate on initial ws connection django_middlewhere = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', # need to check csrf but unable to set that in the http request initiating ws, probably set it in query ] # build a django request from ws request/scope self.scope['method'] = 'WEBSOCKET' request = AsgiRequest(self.scope, '') # get channel's django middleware middleware = [ import_string(m)(lambda x: None) for m in django_middlewhere ] # make sure ws request passes channel's django middleware for m in middleware: if m.process_request(request): raise DenyConnection() # set session and user if hasattr(request, 'session'): self.session = request.session if hasattr(request, 'user'): self.user = request.user # deny if we don't have a session and an authenticated user if not self.session or not self.user or not self.user.is_authenticated: raise DenyConnection()
def connect(self): headers = dict(self.scope["headers"]) if b"authorization" not in headers: LOGGER.warning("WS Request without authorization header") raise DenyConnection() raw_header = headers[b"authorization"] token = token_from_header(raw_header) if not token: LOGGER.warning("Failed to authenticate") raise DenyConnection() self.user = token.user
async def connect(self): self.room_name = self.scope['url_route']['kwargs']['game_id'] self.room_group_name = f'Game_{self.room_name}' if self.scope['user'] == AnonymousUser(): raise DenyConnection("Invalid User") await self.channel_layer.group_add( self.room_group_name, self.channel_name ) # If invalid game id then deny the connection. try: self.game = Game.objects.get(pk=self.room_name) except ObjectDoesNotExist: raise DenyConnection("Invalid Game Id") await self.accept()
def connect(self): super().connect() uuid = self.scope["url_route"]["kwargs"]["pk"] outpost = (get_objects_for_user( self.user, "authentik_outposts.view_outpost").filter(pk=uuid).first()) if not outpost: raise DenyConnection() self.logger = get_logger().bind(outpost=outpost) try: self.accept() except RuntimeError as exc: self.logger.warning("runtime error during accept", exc=exc) raise DenyConnection() self.outpost = outpost self.last_uid = self.channel_name
def receive_json(self, content: Data): msg = from_dict(WebsocketMessage, content) uid = msg.args.get("uuid", self.channel_name) self.last_uid = uid if not self.outpost: raise DenyConnection() state = OutpostState.for_instance_uid(self.outpost, uid) if self.channel_name not in state.channel_ids: state.channel_ids.append(self.channel_name) state.last_seen = datetime.now() if not self.first_msg: GAUGE_OUTPOSTS_CONNECTED.labels( outpost=self.outpost.name, uid=self.last_uid, ).inc() self.first_msg = True if msg.instruction == WebsocketMessageInstruction.HELLO: state.version = msg.args.get("version", None) state.build_hash = msg.args.get("buildHash", "") elif msg.instruction == WebsocketMessageInstruction.ACK: return GAUGE_OUTPOSTS_LAST_UPDATE.labels( outpost=self.outpost.name, uid=self.last_uid or "", version=state.version or "", ).set_to_current_time() state.save(timeout=OUTPOST_HELLO_INTERVAL * 1.5) response = WebsocketMessage( instruction=WebsocketMessageInstruction.ACK) self.send_json(asdict(response))
async def connect(self): if await self.get_workflow() is None: raise DenyConnection() await self.channel_layer.group_add(self.workflow_channel_name, self.channel_name) await self.accept()
def _get_room(self) -> GameRoom: game_room = GameRoom.objects.get(permanent_url=self.room_name) if game_room is None: raise DenyConnection('Game not exist.') return game_room
async def connect(self): try: workflow = await self._read_requested_workflow_with_auth() self.workflow_id = workflow.id except Workflow.DoesNotExist: raise DenyConnection() # not found, or not authorized self.workflow_channel_name = "workflow-%d" % self.workflow_id await self.channel_layer.group_add(self.workflow_channel_name, self.channel_name) logger.debug("Added to channel %s", self.workflow_channel_name) if self.scope["user"].is_authenticated: self.user_channel_name = "user-%d" % self.scope["user"].id await self.channel_layer.group_add(self.user_channel_name, self.channel_name) logger.debug("Added to channel %s", self.user_channel_name) await self.accept() # Solve a race: # # 1. User loads a workflow that isn't rendered, triggering render # 2. Server sends "busy" workflow # 3. Render completes # 4. User connects over Websockets # # Expected results: user sees completed render await self._send_whole_workflow_to_client()
def connect(self): if not self._authenticated(): raise DenyConnection() else: async_to_sync(self.channel_layer.group_add)( 'status_updates', self.channel_name) raise AcceptConnection()
def connect(self): if self.scope['user'] == AnonymousUser(): raise DenyConnection('Need authorization') async_to_sync(self.channel_layer.group_add)(GROUP_NAME, self.channel_name) self.accept()
def connect(self): headers = dict(self.scope["headers"]) if b"authorization" not in headers: LOGGER.warning("WS Request without authorization header") raise DenyConnection() raw_header = headers[b"authorization"] try: token = token_from_header(raw_header) # token is only None when no header was given, in which case we deny too if not token: raise DenyConnection() except AuthenticationFailed as exc: LOGGER.warning("Failed to authenticate", exc=exc) raise DenyConnection() self.user = token.user
async def receive_json(self, content, **kwargs): # Send message to room group action = content.get('action') account_name = content.get('account') await self.check_user_data(account_name) if action == 'subscribe': await self.action_subscribe() elif action == 'unsubscribe': await self.action_unsubscribe() else: raise DenyConnection("wrong action")
async def connect(self): if self.scope['user'] == AnonymousUser(): raise DenyConnection("Invalid User") user = self.scope["user"] user_id = user.id self.group_name = f"{user_id}" await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept()
async def connect(self): if not await DBASYNC(self.current_user.has_perm)(self.PERM_CODE): logger.debug( f'{self.current_user} has no permission.({self.PERM_CODE})') raise DenyConnection('permission error') self.group_name = self.get_group_name(self.current_user) # Join room group await self.channel_layer.group_add(self.group_name, self.channel_name) await self.accept()
def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = self.room_name self.user = self.scope['user'] self.in_room = self.inGroup(self.room_group_name, self.user) if self.in_room == True: async_to_sync(self.channel_layer.group_add)(self.room_group_name, self.channel_name) self.accept() else: raise DenyConnection("Invalid User")
async def connect(self): self.task_id = self.scope['url_route']['kwargs']['task_id'] self.task_group_name = 'task_{}'.format(self.task_id) self.user = self.scope['user'] task = Todo.objects.get(pk=self.task_id) self.task = task if self.user.username: await self.channel_layer.group_add(self.task_group_name, self.channel_name) await self.accept() else: raise DenyConnection('Unauthorized')
async def __call__(self, receive, send): close_old_connections() try: token = parse_qs(self.scope["query_string"].decode("utf8"))["token"][0] except KeyError: raise DenyConnection("Key Error, expected query string token='actual_token") try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) except jwt.ExpiredSignatureError: raise DenyConnection("Token has expired") except IndexError: raise DenyConnection("Auth failed") except: raise DenyConnection("Auth failed") user = await get_user(payload['user_id']) if not user: raise DenyConnection("Invalid User") self.scope['user'] = user inner = self.inner(self.scope) return await inner(receive, send)
def connect(self): super().connect() uuid = self.scope["url_route"]["kwargs"]["pk"] outpost = get_objects_for_user( self.user, "authentik_outposts.view_outpost").filter(pk=uuid) if not outpost.exists(): raise DenyConnection() self.accept() self.outpost = outpost.first() self.last_uid = self.channel_name LOGGER.debug( "added outpost instace to cache", outpost=self.outpost, channel_name=self.channel_name, )
async def connect(self): #getting ip address of client self.ip=self.scope['client'][0] try: #check ip already available in database self.device= sync_to_async(Ip.objects.get)(address=self.ip) except ObjectDoesNotExist: #if ip address not exist raise error raise DenyConnection("Invalid User") await self.channel_layer.group_add(self.groupname, self.channel_name) await self.accept() print(self.scope['client'][0])
async def connect(self): # user = self.scope['user'] user = await get_user(self.scope) if user == AnonymousUser(): raise DenyConnection("Invalid User") self.room_name = f"{self.room_name_prefix}{user.id}" self.room_group_name = f"{self.room_group_name_prefix}{self.room_name}" # Join room group await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() print("connected")
def connect(self): self.service = self.scope["service"] scope = dict(self.scope) scope["method"] = "get" request = AsgiRequest(scope, b"") request._request = request request.user = self.scope["user"] request.session = self.scope["session"] if not self.scope["user"].is_authenticated: self.authenticate(request) if self.check_permissions(request): raise AcceptConnection() else: raise DenyConnection()
async def connect(self): # Verify try: self.feature = await db_sync_to_async(lambda: Feature.objects.get( slug=self.scope["url_route"]["kwargs"]["feature_slug"]))() except Feature.DoesNotExist: raise DenyConnection() await db_sync_to_async(self.scope["session"].save)() await self.channel_layer.group_add(self.feature.slug, self.channel_name) # Accept await self.accept() # Broadcast state await state.broadcast_feature_state(self.feature)
async def connect(self): self.session_id = self.scope['url_route']['kwargs']['session_id'] self.player_id = self.scope['url_route']['kwargs']['player_id'] try: GameSession.get_by_id(self.session_id) except: raise DenyConnection('invalid session id') await self.channel_layer.group_add( self.session_id.__str__(), self.channel_name ) await self.accept() await self.send_game_data() Statistic.players_now += 1
async def connect(self): comment_of = self.scope["url_route"]["kwargs"]["comment_of"] of_id = self.scope["url_route"]["kwargs"]["of_id"] self.room_name = f"{comment_of}_{of_id}" self.room_group_name = f"group_{self.room_name}" user = await get_user(self.scope) if user == AnonymousUser(): raise DenyConnection("Invalid User") # Join room group await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() print("connected")
async def connect(self): if not await self.authorize('read'): raise DenyConnection() await self.channel_layer.group_add(self.workflow_channel_name, self.channel_name) logger.debug('Added to channel %s', self.workflow_channel_name) await self.accept() # Solve a race: # # 1. User loads a workflow that isn't rendered, triggering render # 2. Server sends "busy" workflow # 3. Render completes # 4. User connects over Websockets # # Expected results: user sees completed render await self.send_whole_workflow_to_client()
async def connect(self): if self.scope['user'] == AnonymousUser(): raise DenyConnection("Такого пользователя не существует") self.chat_id = self.scope['url_route']['kwargs']['chat_id'] try: chat = await get_user_chat(pk=self.chat_id, user=self.scope['user']) self.chat_group_name = f'chat_{chat.id}' # Join room group await self.channel_layer.group_add(self.chat_group_name, self.channel_name) await self.accept() except ObjectDoesNotExist: await self.close()
def connect(self): super().connect() uuid = self.scope["url_route"]["kwargs"]["pk"] outpost = get_objects_for_user( self.user, "authentik_outposts.view_outpost").filter(pk=uuid) if not outpost.exists(): raise DenyConnection() self.accept() self.outpost = outpost.first() OutpostState( uid=self.channel_name, last_seen=datetime.now(), _outpost=self.outpost).save(timeout=OUTPOST_HELLO_INTERVAL * 1.5) LOGGER.debug( "added outpost instace to cache", outpost=self.outpost, channel_name=self.channel_name, )
async def connect(self): self.room_name = self.scope['url_route']['kwargs']['id'] self.room_group_name = 'notification_%s' % self.room_name self.user = self.scope['user'] self.file_id = self.room_name # Repo.delete("comments") # Join room group if self.user.username: await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() comments = Repo.search("comments", { "user_id": self.user.id, "file_id": self.file_id }) await self.send(text_data=json.dumps({ "status": "list", "data": comments })) else: raise DenyConnection("Only Authorized user can connect socket")
async def connect(self): self.user = self.scope["user"] if self.user.is_anonymous: await self.accept() await self.close(code=4000) else: self.meetup_name = self.scope["url_route"]["kwargs"]["room_name"] self.meetup_group_name = "meetup_%s" % self.meetup_name await self.channel_layer.group_add(self.meetup_group_name, self.channel_name) try: self.meetup = await database_sync_to_async( Meetup.objects.get)(uri=self.meetup_name) except ObjectDoesNotExist: print("INVALID") raise DenyConnection("Invalid Meetup URI") await self.accept()
async def connect(self): for key in self.scope.keys(): logging.getLogger(__name__).debug( "SCOPE[{}] = {}".format(key, self.scope[key]) ) self.group_name = self.scope["url_route"]["kwargs"]["room_name"] (self.context, self.collection, self.target) = self.group_name.split("--") self.wsid = "{}--{}".format( self.group_name, self.scope.get("hx_user_id", "unknown") ) logging.getLogger(__name__).debug( "{}|channel_name({}), context({}), collection({}), object({}), user({})".format( self.wsid, self.channel_name, self.context, self.collection, self.target, self.scope["hx_user_id"], ) ) auth = self.scope["hxat_auth"] if auth != "authenticated": logging.getLogger(__name__).debug( "{}|ws auth FAILED: {}, dropping connection".format(self.wsid, auth) ) raise DenyConnection() # return status_code=403 else: # join room group await self.channel_layer.group_add(self.group_name, self.channel_name) logging.getLogger(__name__).debug( "{}|added group to channel({})".format(self.wsid, self.channel_name) ) await self.accept() logging.getLogger(__name__).debug( "{}|CONNECTION ACCEPTED".format(self.wsid) )