How to use the synapse.rest.client.v2_alpha._base.client_patterns function in synapse

To help you get started, we’ve selected a few synapse examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github matrix-org / synapse / synapse / rest / client / v2_alpha / keys.py View on Github external
],
            "keys": { // Must include a ed25519 signing key
              ":": "",
            },
            "signatures:" {
              // Must be signed with device's ed25519 key
              "/": {
                ":": ""
              }
              // Must be signed by this server.
              "": {
                ":": ""
    } } } } } }
    """

    PATTERNS = client_patterns("/keys/query$")

    def __init__(self, hs):
        """
        Args:
            hs (synapse.server.HomeServer):
        """
        super(KeyQueryServlet, self).__init__()
        self.auth = hs.get_auth()
        self.e2e_keys_handler = hs.get_e2e_keys_handler()

    async def on_POST(self, request):
        requester = await self.auth.get_user_by_req(request, allow_guest=True)
        user_id = requester.user.to_string()
        timeout = parse_integer(request, "timeout", 10 * 1000)
        body = parse_json_object_from_request(request)
        result = await self.e2e_keys_handler.query_devices(body, timeout, user_id)
github matrix-org / synapse / synapse / rest / client / v1 / room.py View on Github external
http_server.register_paths(
        "POST",
        client_patterns(regex_string + "$", v1=True),
        servlet.on_POST,
        servlet.__class__.__name__,
    )
    http_server.register_paths(
        "PUT",
        client_patterns(regex_string + "/(?P[^/]*)$", v1=True),
        servlet.on_PUT,
        servlet.__class__.__name__,
    )
    if with_get:
        http_server.register_paths(
            "GET",
            client_patterns(regex_string + "/(?P[^/]*)$", v1=True),
            servlet.on_GET,
            servlet.__class__.__name__,
        )
github matrix-org / synapse / synapse / rest / client / v2_alpha / account.py View on Github external
Codes.THREEPID_DENIED,
            )

        existingUid = yield self.datastore.get_user_id_by_threepid(
            'msisdn', msisdn
        )

        if existingUid is not None:
            raise SynapseError(400, "MSISDN is already in use", Codes.THREEPID_IN_USE)

        ret = yield self.identity_handler.requestMsisdnToken(**body)
        defer.returnValue((200, ret))


class ThreepidRestServlet(RestServlet):
    PATTERNS = client_patterns("/account/3pid$")

    def __init__(self, hs):
        super(ThreepidRestServlet, self).__init__()
        self.hs = hs
        self.identity_handler = hs.get_handlers().identity_handler
        self.auth = hs.get_auth()
        self.auth_handler = hs.get_auth_handler()
        self.datastore = self.hs.get_datastore()

    @defer.inlineCallbacks
    def on_GET(self, request):
        requester = yield self.auth.get_user_by_req(request)

        threepids = yield self.datastore.user_get_threepids(
            requester.user.to_string()
        )
github matrix-org / synapse / synapse / rest / client / v1 / events.py View on Github external
# See the License for the specific language governing permissions and
# limitations under the License.

"""This module contains REST servlets to do with event streaming, /events."""
import logging

from synapse.api.errors import SynapseError
from synapse.http.servlet import RestServlet
from synapse.rest.client.v2_alpha._base import client_patterns
from synapse.streams.config import PaginationConfig

logger = logging.getLogger(__name__)


class EventStreamRestServlet(RestServlet):
    PATTERNS = client_patterns("/events$", v1=True)

    DEFAULT_LONGPOLL_TIME_MS = 30000

    def __init__(self, hs):
        super(EventStreamRestServlet, self).__init__()
        self.event_stream_handler = hs.get_event_stream_handler()
        self.auth = hs.get_auth()

    async def on_GET(self, request):
        requester = await self.auth.get_user_by_req(request, allow_guest=True)
        is_guest = requester.is_guest
        room_id = None
        if is_guest:
            if b"room_id" not in request.args:
                raise SynapseError(400, "Guest users must specify room_id param")
        if b"room_id" in request.args:
github matrix-org / synapse / synapse / rest / client / v2_alpha / account_data.py View on Github external
from synapse.api.errors import AuthError, NotFoundError, SynapseError
from synapse.http.servlet import RestServlet, parse_json_object_from_request

from ._base import client_patterns

logger = logging.getLogger(__name__)


class AccountDataServlet(RestServlet):
    """
    PUT /user/{user_id}/account_data/{account_dataType} HTTP/1.1
    GET /user/{user_id}/account_data/{account_dataType} HTTP/1.1
    """

    PATTERNS = client_patterns(
        "/user/(?P[^/]*)/account_data/(?P[^/]*)"
    )

    def __init__(self, hs):
        super(AccountDataServlet, self).__init__()
        self.auth = hs.get_auth()
        self.store = hs.get_datastore()
        self.notifier = hs.get_notifier()

    async def on_PUT(self, request, user_id, account_data_type):
        requester = await self.auth.get_user_by_req(request)
        if user_id != requester.user.to_string():
            raise AuthError(403, "Cannot add account data for other users.")

        body = parse_json_object_from_request(request)
github matrix-org / synapse / synapse / rest / client / v1 / pusher.py View on Github external
)

        self.notifier.on_new_replication_data()

        return 200, {}

    def on_OPTIONS(self, _):
        return 200, {}


class PushersRemoveRestServlet(RestServlet):
    """
    To allow pusher to be delete by clicking a link (ie. GET request)
    """

    PATTERNS = client_patterns("/pushers/remove$", v1=True)
    SUCCESS_HTML = b"You have been unsubscribed"

    def __init__(self, hs):
        super(PushersRemoveRestServlet, self).__init__()
        self.hs = hs
        self.notifier = hs.get_notifier()
        self.auth = hs.get_auth()
        self.pusher_pool = self.hs.get_pusherpool()

    async def on_GET(self, request):
        requester = await self.auth.get_user_by_req(request, rights="delete_pusher")
        user = requester.user

        app_id = parse_string(request, "app_id", required=True)
        pushkey = parse_string(request, "pushkey", required=True)
github matrix-org / synapse / synapse / rest / client / v2_alpha / capabilities.py View on Github external
# See the License for the specific language governing permissions and
# limitations under the License.
import logging

from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
from synapse.http.servlet import RestServlet

from ._base import client_patterns

logger = logging.getLogger(__name__)


class CapabilitiesRestServlet(RestServlet):
    """End point to expose the capabilities of the server."""

    PATTERNS = client_patterns("/capabilities$")

    def __init__(self, hs):
        """
        Args:
            hs (synapse.server.HomeServer): server
        """
        super(CapabilitiesRestServlet, self).__init__()
        self.hs = hs
        self.config = hs.config
        self.auth = hs.get_auth()
        self.store = hs.get_datastore()

    async def on_GET(self, request):
        requester = await self.auth.get_user_by_req(request, allow_guest=True)
        user = await self.store.get_user_by_id(requester.user.to_string())
        change_password = bool(user["password_hash"])
github matrix-org / synapse / synapse / rest / client / v1 / directory.py View on Github external
)
from synapse.http.servlet import RestServlet, parse_json_object_from_request
from synapse.rest.client.v2_alpha._base import client_patterns
from synapse.types import RoomAlias

logger = logging.getLogger(__name__)


def register_servlets(hs, http_server):
    ClientDirectoryServer(hs).register(http_server)
    ClientDirectoryListServer(hs).register(http_server)
    ClientAppserviceDirectoryListServer(hs).register(http_server)


class ClientDirectoryServer(RestServlet):
    PATTERNS = client_patterns("/directory/room/(?P[^/]*)$", v1=True)

    def __init__(self, hs):
        super(ClientDirectoryServer, self).__init__()
        self.store = hs.get_datastore()
        self.handlers = hs.get_handlers()
        self.auth = hs.get_auth()

    async def on_GET(self, request, room_alias):
        room_alias = RoomAlias.from_string(room_alias)

        dir_handler = self.handlers.directory_handler
        res = await dir_handler.get_association(room_alias)

        return 200, res

    async def on_PUT(self, request, room_alias):
github matrix-org / synapse / synapse / rest / client / v1 / room.py View on Github external
third_party_instance_id=third_party_instance_id,
            )
        else:
            data = await handler.get_local_public_room_list(
                limit=limit,
                since_token=since_token,
                search_filter=search_filter,
                network_tuple=network_tuple,
            )

        return 200, data


# TODO: Needs unit testing
class RoomMemberListRestServlet(RestServlet):
    PATTERNS = client_patterns("/rooms/(?P[^/]*)/members$", v1=True)

    def __init__(self, hs):
        super(RoomMemberListRestServlet, self).__init__()
        self.message_handler = hs.get_message_handler()
        self.auth = hs.get_auth()

    async def on_GET(self, request, room_id):
        # TODO support Pagination stream API (limit/tokens)
        requester = await self.auth.get_user_by_req(request)
        handler = self.message_handler

        # request the state as of a given event, as identified by a stream token,
        # for consistency with /messages etc.
        # useful for getting the membership in retrospect as of a given /sync
        # response.
        at_token_string = parse_string(request, "at")
github matrix-org / synapse / synapse / rest / client / v2_alpha / thirdparty.py View on Github external
self.appservice_handler = hs.get_application_service_handler()

    async def on_GET(self, request, protocol):
        await self.auth.get_user_by_req(request, allow_guest=True)

        protocols = await self.appservice_handler.get_3pe_protocols(
            only_protocol=protocol
        )
        if protocol in protocols:
            return 200, protocols[protocol]
        else:
            return 404, {"error": "Unknown protocol"}


class ThirdPartyUserServlet(RestServlet):
    PATTERNS = client_patterns("/thirdparty/user(/(?P[^/]+))?$")

    def __init__(self, hs):
        super(ThirdPartyUserServlet, self).__init__()

        self.auth = hs.get_auth()
        self.appservice_handler = hs.get_application_service_handler()

    async def on_GET(self, request, protocol):
        await self.auth.get_user_by_req(request, allow_guest=True)

        fields = request.args
        fields.pop(b"access_token", None)

        results = await self.appservice_handler.query_3pe(
            ThirdPartyEntityKind.USER, protocol, fields
        )