How to use the synapse.api.errors.Codes 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 / tests / federation / test_complexity.py View on Github external
d = handler._remote_join(
            None,
            ["other.example.com"],
            room_1,
            UserID.from_string(u1),
            {"membership": "join"},
        )

        self.pump()

        # The request failed with a SynapseError saying the resource limit was
        # exceeded.
        f = self.get_failure(d, SynapseError)
        self.assertEqual(f.value.code, 400)
        self.assertEqual(f.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
github matrix-org / synapse / synapse / handlers / register.py View on Github external
def check_username(self, localpart, guest_access_token=None,
                       assigned_user_id=None):
        if types.contains_invalid_mxid_characters(localpart):
            raise SynapseError(
                400,
                "User ID can only contain characters a-z, 0-9, or '=_-./'",
                Codes.INVALID_USERNAME
            )

        if not localpart:
            raise SynapseError(
                400,
                "User ID cannot be empty",
                Codes.INVALID_USERNAME
            )

        if localpart[0] == '_':
            raise SynapseError(
                400,
                "User ID may not begin with _",
                Codes.INVALID_USERNAME
            )
github matrix-org / synapse / synapse / rest / client / v2_alpha / account.py View on Github external
def on_POST(self, request):
        body = parse_json_object_from_request(request)

        threePidCreds = body.get('threePidCreds')
        threePidCreds = body.get('three_pid_creds', threePidCreds)
        if threePidCreds is None:
            raise SynapseError(400, "Missing param", Codes.MISSING_PARAM)

        requester = yield self.auth.get_user_by_req(request)
        user_id = requester.user.to_string()

        threepid = yield self.identity_handler.threepid_from_creds(threePidCreds)

        if not threepid:
            raise SynapseError(
                400, "Failed to auth 3pid", Codes.THREEPID_AUTH_FAILED
            )

        for reqd in ['medium', 'address', 'validated_at']:
            if reqd not in threepid:
                logger.warn("Couldn't add 3pid: invalid response from ID server")
                raise SynapseError(500, "Invalid response from ID Server")

        yield self.auth_handler.add_threepid(
            user_id,
            threepid['medium'],
            threepid['address'],
            threepid['validated_at'],
        )

        if 'bind' in body and body['bind']:
            logger.debug(
github matrix-org / synapse / synapse / http / servlet.py View on Github external
def parse_integer_from_args(args, name, default=None, required=False):

    if not isinstance(name, bytes):
        name = name.encode("ascii")

    if name in args:
        try:
            return int(args[name][0])
        except Exception:
            message = "Query parameter %r must be an integer" % (name,)
            raise SynapseError(400, message, errcode=Codes.INVALID_PARAM)
    else:
        if required:
            message = "Missing integer query parameter %r" % (name,)
            raise SynapseError(400, message, errcode=Codes.MISSING_PARAM)
        else:
            return default
github matrix-org / synapse / synapse / handlers / federation.py View on Github external
try:
            event, context = yield self.event_creation_handler.create_new_client_event(
                builder=builder
            )
        except AuthError as e:
            logger.warning("Failed to create join to %s because %s", room_id, e)
            raise e

        event_allowed = yield self.third_party_event_rules.check_event_allowed(
            event, context
        )
        if not event_allowed:
            logger.info("Creation of join %s forbidden by third-party rules", event)
            raise SynapseError(
                403, "This event is not allowed in this context", Codes.FORBIDDEN
            )

        # The remote hasn't signed it yet, obviously. We'll do the full checks
        # when we get the event back in `on_send_join_request`
        yield self.auth.check_from_context(
            room_version, event, context, do_sig_check=False
        )

        return event
github matrix-org / synapse / synapse / handlers / ui_auth / checkers.py View on Github external
def _check_threepid(self, medium, authdict):
        if "threepid_creds" not in authdict:
            raise LoginError(400, "Missing threepid_creds", Codes.MISSING_PARAM)

        threepid_creds = authdict["threepid_creds"]

        identity_handler = self.hs.get_handlers().identity_handler

        logger.info("Getting validated threepid. threepidcreds: %r", (threepid_creds,))

        # msisdns are currently always ThreepidBehaviour.REMOTE
        if medium == "msisdn":
            if not self.hs.config.account_threepid_delegate_msisdn:
                raise SynapseError(
                    400, "Phone number verification is not enabled on this homeserver"
                )
            threepid = yield identity_handler.threepid_from_creds(
                self.hs.config.account_threepid_delegate_msisdn, threepid_creds
            )
github matrix-org / synapse / synapse / rest / client / v2_alpha / report_event.py View on Github external
async def on_POST(self, request, room_id, event_id):
        requester = await self.auth.get_user_by_req(request)
        user_id = requester.user.to_string()

        body = parse_json_object_from_request(request)
        assert_params_in_dict(body, ("reason", "score"))

        if not isinstance(body["reason"], string_types):
            raise SynapseError(
                http_client.BAD_REQUEST,
                "Param 'reason' must be a string",
                Codes.BAD_JSON,
            )
        if not isinstance(body["score"], int):
            raise SynapseError(
                http_client.BAD_REQUEST,
                "Param 'score' must be an integer",
                Codes.BAD_JSON,
            )

        await self.store.add_event_report(
            room_id=room_id,
            event_id=event_id,
            user_id=user_id,
            reason=body["reason"],
            content=body,
            received_ts=self.clock.time_msec(),
        )
github matrix-org / synapse / synapse / handlers / ui_auth / checkers.py View on Github external
"address": row["address"],
                        "validated_at": row["validated_at"],
                    }

                    # Valid threepid returned, delete from the db
                    yield self.store.delete_threepid_session(threepid_creds["sid"])
            else:
                raise SynapseError(
                    400, "Email address verification is not enabled on this homeserver"
                )
        else:
            # this can't happen!
            raise AssertionError("Unrecognized threepid medium: %s" % (medium,))

        if not threepid:
            raise LoginError(401, "", errcode=Codes.UNAUTHORIZED)

        if threepid["medium"] != medium:
            raise LoginError(
                401,
                "Expecting threepid of type '%s', got '%s'"
                % (medium, threepid["medium"]),
                errcode=Codes.UNAUTHORIZED,
            )

        threepid["threepid_creds"] = authdict["threepid_creds"]

        return threepid
github matrix-org / synapse / synapse / handlers / password_policy.py View on Github external
Raises:
            PasswordRefusedError: The password doesn't comply with the server's policy.
        """

        if not self.enabled:
            return

        minimum_accepted_length = self.policy.get("minimum_length", 0)
        if len(password) < minimum_accepted_length:
            raise PasswordRefusedError(
                msg=(
                    "The password must be at least %d characters long"
                    % minimum_accepted_length
                ),
                errcode=Codes.PASSWORD_TOO_SHORT,
            )

        if (
            self.policy.get("require_digit", False) and
            self.regexp_digit.search(password) is None
        ):
            raise PasswordRefusedError(
                msg="The password must include at least one digit",
                errcode=Codes.PASSWORD_NO_DIGIT,
            )

        if (
            self.policy.get("require_symbol", False) and
            self.regexp_symbol.search(password) is None
        ):
            raise PasswordRefusedError(
github matrix-org / synapse / synapse / rest / client / v1 / admin.py View on Github external
404,
                    "there is no event to be purged",
                    errcode=Codes.NOT_FOUND,
                )
            (stream, topo, _event_id) = r
            token = "t%d-%d" % (topo, stream)
            logger.info(
                "[purge] purging up to token %s (received_ts %i => "
                "stream_ordering %i)",
                token, ts, stream_ordering,
            )
        else:
            raise SynapseError(
                400,
                "must specify purge_up_to_event_id or purge_up_to_ts",
                errcode=Codes.BAD_JSON,
            )

        purge_id = yield self.pagination_handler.start_purge_history(
            room_id, token,
            delete_local_events=delete_local_events,
        )

        defer.returnValue((200, {
            "purge_id": purge_id,
        }))