Example #1
0
File: socket.py Project: zag/zulip
    def authenticate_client(self, msg):
        if self.authenticated:
            self.session.send_message({
                'req_id': msg['req_id'],
                'type': 'response',
                'response': {
                    'result': 'error',
                    'msg': 'Already authenticated'
                }
            })
            return

        user_profile = get_user_profile(self.browser_session_id)
        if user_profile is None:
            raise SocketAuthError('Unknown or missing session')
        self.session.user_profile = user_profile

        if msg['request']['csrf_token'] != self.csrf_token:
            raise SocketAuthError('CSRF token does not match that in cookie')

        if not 'queue_id' in msg['request']:
            raise SocketAuthError("Missing 'queue_id' argument")

        queue_id = msg['request']['queue_id']
        client = get_client_descriptor(queue_id)
        if client is None:
            raise SocketAuthError('Bad event queue id: %s' % (queue_id, ))

        if user_profile.id != client.user_profile_id:
            raise SocketAuthError(
                "You are not the owner of the queue with id '%s'" %
                (queue_id, ))

        self.authenticated = True
        register_connection(queue_id, self)

        response = {
            'req_id': msg['req_id'],
            'type': 'response',
            'response': {
                'result': 'success',
                'msg': ''
            }
        }

        status_inquiries = msg['request'].get('status_inquiries')
        if status_inquiries is not None:
            results = {}
            for inquiry in status_inquiries:
                status = redis_client.hgetall(req_redis_key(inquiry))
                if len(status) == 0:
                    status['status'] = 'not_received'
                if 'response' in status:
                    status['response'] = ujson.loads(status['response'])
                results[str(inquiry)] = status
            response['response']['status_inquiries'] = results

        self.session.send_message(response)
        ioloop = tornado.ioloop.IOLoop.instance()
        ioloop.remove_timeout(self.timeout_handle)
Example #2
0
def cleanup_event_queue(request, user_profile, queue_id=REQ()):
    client = get_client_descriptor(queue_id)
    if client is None:
        return json_error("Bad event queue id: %s" % (queue_id,))
    if user_profile.id != client.user_profile_id:
        return json_error("You are not authorized to access this queue")
    request._log_data['extra'] = "[%s]" % (queue_id,)
    client.cleanup()
    return json_success()
Example #3
0
def cleanup_event_queue(request, user_profile, queue_id=REQ()):
    # type: (HttpRequest, UserProfile, text_type) -> HttpResponse
    client = get_client_descriptor(str(queue_id))
    if client is None:
        return json_error(_("Bad event queue id: %s") % (queue_id, ))
    if user_profile.id != client.user_profile_id:
        return json_error(_("You are not authorized to access this queue"))
    request._log_data['extra'] = "[%s]" % (queue_id, )
    client.cleanup()
    return json_success()
Example #4
0
def cleanup_event_queue(request, user_profile, queue_id=REQ()):
    # type: (HttpRequest, UserProfile, text_type) -> HttpResponse
    client = get_client_descriptor(queue_id)
    if client is None:
        return json_error(_("Bad event queue id: %s") % (queue_id,))
    if user_profile.id != client.user_profile_id:
        return json_error(_("You are not authorized to access this queue"))
    request._log_data["extra"] = "[%s]" % (queue_id,)
    client.cleanup()
    return json_success()
Example #5
0
def get_events_backend(request, user_profile, handler = None,
                       user_client = REQ(converter=get_client, default=None),
                       last_event_id = REQ(converter=int, default=None),
                       queue_id = REQ(default=None),
                       apply_markdown = REQ(default=False, validator=check_bool),
                       all_public_streams = REQ(default=False, validator=check_bool),
                       event_types = REQ(default=None, validator=check_list(check_string)),
                       dont_block = REQ(default=False, validator=check_bool),
                       narrow = REQ(default=[], validator=check_list(None)),
                       lifespan_secs = REQ(default=0, converter=int)):
    if user_client is None:
        user_client = request.client

    was_connected = False
    orig_queue_id = queue_id
    if queue_id is None:
        if dont_block:
            client = allocate_client_descriptor(user_profile.id, user_profile.realm.id,
                                                event_types, user_client, apply_markdown,
                                                all_public_streams, lifespan_secs,
                                                narrow=narrow)
            queue_id = client.event_queue.id
        else:
            return json_error("Missing 'queue_id' argument")
    else:
        if last_event_id is None:
            return json_error("Missing 'last_event_id' argument")
        client = get_client_descriptor(queue_id)
        if client is None:
            return json_error("Bad event queue id: %s" % (queue_id,))
        if user_profile.id != client.user_profile_id:
            return json_error("You are not authorized to get events from this queue")
        client.event_queue.prune(last_event_id)
        was_connected = client.finish_current_handler()

    if not client.event_queue.empty() or dont_block:
        ret = {'events': client.event_queue.contents()}
        if orig_queue_id is None:
            ret['queue_id'] = queue_id
        request._log_data['extra'] = "[%s/%s]" % (queue_id, len(ret["events"]))
        if was_connected:
            request._log_data['extra'] += " [was connected]"
        return json_success(ret)

    handler._request = request
    if was_connected:
        logging.info("Disconnected handler for queue %s (%s/%s)" % (queue_id, user_profile.email,
                                                                    user_client.name))
    client.connect_handler(handler)

    # runtornado recognizes this special return value.
    return RespondAsynchronously
Example #6
0
    def authenticate_client(self, msg):
        # type: (Dict[str, Any]) -> None
        if self.authenticated:
            self.session.send_message({'req_id': msg['req_id'], 'type': 'response',
                                       'response': {'result': 'error', 'msg': 'Already authenticated'}})
            return

        user_profile = get_user_profile(self.browser_session_id)
        if user_profile is None:
            raise SocketAuthError('Unknown or missing session')
        self.session.user_profile = user_profile

        if not _compare_salted_tokens(msg['request']['csrf_token'], self.csrf_token):
            raise SocketAuthError('CSRF token does not match that in cookie')

        if 'queue_id' not in msg['request']:
            raise SocketAuthError("Missing 'queue_id' argument")

        queue_id = msg['request']['queue_id']
        client = get_client_descriptor(queue_id)
        if client is None:
            raise SocketAuthError('Bad event queue id: %s' % (queue_id,))

        if user_profile.id != client.user_profile_id:
            raise SocketAuthError("You are not the owner of the queue with id '%s'" % (queue_id,))

        self.authenticated = True
        register_connection(queue_id, self)

        response = {'req_id': msg['req_id'], 'type': 'response',
                    'response': {'result': 'success', 'msg': ''}}

        status_inquiries = msg['request'].get('status_inquiries')
        if status_inquiries is not None:
            results = {}
            for inquiry in status_inquiries:
                status = redis_client.hgetall(req_redis_key(inquiry))
                if len(status) == 0:
                    status['status'] = 'not_received'
                if 'response' in status:
                    status['response'] = ujson.loads(status['response'])
                results[str(inquiry)] = status
            response['response']['status_inquiries'] = results

        self.session.send_message(response)
        ioloop = tornado.ioloop.IOLoop.instance()
        ioloop.remove_timeout(self.timeout_handle)