def to_wild_value(var_name: str, input: str) -> WildValue: try: value = orjson.loads(input) except orjson.JSONDecodeError: raise InvalidJSONError(_("Malformed JSON")) return wrap_wild_value(var_name, value)
def api_slack_incoming_webhook( request: HttpRequest, user_profile: UserProfile, user_specified_topic: Optional[str] = REQ("topic", default=None), ) -> HttpResponse: # Slack accepts webhook payloads as payload="encoded json" as # application/x-www-form-urlencoded, as well as in the body as # application/json. if request.content_type == "application/json": try: val = request.body.decode(request.encoding or "utf-8") except UnicodeDecodeError: # nocoverage raise JsonableError(_("Malformed payload")) else: req_var = "payload" if req_var in request.POST: val = request.POST[req_var] elif req_var in request.GET: # nocoverage val = request.GET[req_var] else: raise RequestVariableMissingError(req_var) try: payload = orjson.loads(val) except orjson.JSONDecodeError: # nocoverage raise InvalidJSONError(_("Malformed JSON")) if user_specified_topic is None and "channel" in payload: user_specified_topic = re.sub("^[@#]", "", payload["channel"]) if user_specified_topic is None: user_specified_topic = "(no topic)" body = "" if "blocks" in payload: for block in payload["blocks"]: body = add_block(block, body) if "attachments" in payload: for attachment in payload["attachments"]: body = add_attachment(attachment, body) if body == "" and "text" in payload and payload["text"] is not None: body += payload["text"] if "icon_emoji" in payload and payload["icon_emoji"] is not None: body = "{} {}".format(payload["icon_emoji"], body) if body != "": body = replace_formatting(replace_links(body).strip()) check_send_webhook_message(request, user_profile, user_specified_topic, body) return json_success(request)
def api_slack_incoming_webhook( request: HttpRequest, user_profile: UserProfile, user_specified_topic: Optional[str] = REQ("topic", default=None), payload: Optional[Dict[str, Any]] = REQ('payload', converter=ujson.loads, default=None) ) -> HttpResponse: # Slack accepts webhook payloads as payload="encoded json" as # application/x-www-form-urlencoded, as well as in the body as # application/json. We use has_request_variables to try to get # the form encoded version, and parse the body out ourselves if # # we were given JSON. if payload is None: try: payload = ujson.loads(request.body) except ValueError: # nocoverage raise InvalidJSONError(_("Malformed JSON")) if user_specified_topic is None and "channel" in payload: user_specified_topic = re.sub("^[@#]", "", payload["channel"]) if user_specified_topic is None: user_specified_topic = "(no topic)" body = "" if "blocks" in payload: for block in payload["blocks"]: body = add_block(block, body) if "attachments" in payload: for attachment in payload["attachments"]: body = add_attachment(attachment, body) if body == "" and "text" in payload: body += payload["text"] if "icon_emoji" in payload and payload["icon_emoji"] is not None: body = "{} {}".format(payload["icon_emoji"], body) if body != "": body = replace_formatting(replace_links(body).strip()) check_send_webhook_message(request, user_profile, user_specified_topic, body) return json_success()
def my_webhook(request: HttpRequest, user_profile: UserProfile) -> None: raise InvalidJSONError("Malformed JSON")
def my_webhook_notify(request: HttpRequest, user_profile: UserProfile) -> HttpResponse: raise InvalidJSONError("Malformed JSON")
def _wrapped_view_func(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: for param in post_params: func_var_name = param.func_var_name if param.path_only: # For path_only parameters, they should already have # been passed via the URL, so there's no need for REQ # to do anything. # # TODO: Either run validators for path_only parameters # or don't declare them using REQ. assert func_var_name in kwargs if func_var_name in kwargs: continue assert func_var_name is not None if param.argument_type == 'body': try: val = ujson.loads(request.body) except ValueError: raise InvalidJSONError(_("Malformed JSON")) kwargs[func_var_name] = val continue elif param.argument_type is not None: # This is a view bug, not a user error, and thus should throw a 500. raise Exception(_("Invalid argument type")) post_var_names = [param.post_var_name] post_var_names += param.aliases default_assigned = False post_var_name: Optional[str] = None for req_var in post_var_names: if req_var in request.POST: val = request.POST[req_var] elif req_var in request.GET: val = request.GET[req_var] else: # This is covered by test_REQ_aliases, but coverage.py # fails to recognize this for some reason. continue # nocoverage if post_var_name is not None: assert req_var is not None raise RequestConfusingParmsError(post_var_name, req_var) post_var_name = req_var if post_var_name is None: post_var_name = param.post_var_name assert post_var_name is not None if param.default is _REQ.NotSpecified: raise RequestVariableMissingError(post_var_name) val = param.default default_assigned = True if param.converter is not None and not default_assigned: try: val = param.converter(val) except JsonableError: raise except Exception: raise RequestVariableConversionError(post_var_name, val) # Validators are like converters, but they don't handle JSON parsing; we do. if param.validator is not None and not default_assigned: try: val = ujson.loads(val) except Exception: raise JsonableError(_('Argument "{}" is not valid JSON.').format(post_var_name)) try: val = param.validator(post_var_name, val) except ValidationError as error: raise JsonableError(error.message) # str_validators is like validator, but for direct strings (no JSON parsing). if param.str_validator is not None and not default_assigned: try: val = param.str_validator(post_var_name, val) except ValidationError as error: raise JsonableError(error.message) kwargs[func_var_name] = val return view_func(request, *args, **kwargs)
def _wrapped_view_func(request: HttpRequest, *args: object, **kwargs: object) -> HttpResponse: request_notes = RequestNotes.get_notes(request) for param in post_params: func_var_name = param.func_var_name if param.path_only: # For path_only parameters, they should already have # been passed via the URL, so there's no need for REQ # to do anything. # # TODO: Either run validators for path_only parameters # or don't declare them using REQ. assert func_var_name in kwargs if func_var_name in kwargs: continue assert func_var_name is not None post_var_name: Optional[str] if param.argument_type == "body": post_var_name = "request" try: val = request.body.decode(request.encoding or "utf-8") except UnicodeDecodeError: raise JsonableError(_("Malformed payload")) else: # This is a view bug, not a user error, and thus should throw a 500. assert param.argument_type is None, "Invalid argument type" post_var_names = [param.post_var_name] post_var_names += param.aliases post_var_name = None for req_var in post_var_names: assert req_var is not None if req_var in request.POST: val = request.POST[req_var] request_notes.processed_parameters.add(req_var) elif req_var in request.GET: val = request.GET[req_var] request_notes.processed_parameters.add(req_var) else: # This is covered by test_REQ_aliases, but coverage.py # fails to recognize this for some reason. continue # nocoverage if post_var_name is not None: raise RequestConfusingParmsError( post_var_name, req_var) post_var_name = req_var if post_var_name is None: post_var_name = param.post_var_name assert post_var_name is not None if param.default is _REQ.NotSpecified: raise RequestVariableMissingError(post_var_name) kwargs[func_var_name] = param.default continue if param.converter is not None: try: val = param.converter(post_var_name, val) except JsonableError: raise except Exception: raise RequestVariableConversionError(post_var_name, val) # json_validator is like converter, but doesn't handle JSON parsing; we do. if param.json_validator is not None: try: val = orjson.loads(val) except orjson.JSONDecodeError: if param.argument_type == "body": raise InvalidJSONError(_("Malformed JSON")) raise JsonableError( _('Argument "{}" is not valid JSON.').format( post_var_name)) try: val = param.json_validator(post_var_name, val) except ValidationError as error: raise JsonableError(error.message) # str_validators is like json_validator, but for direct strings (no JSON parsing). if param.str_validator is not None: try: val = param.str_validator(post_var_name, val) except ValidationError as error: raise JsonableError(error.message) kwargs[func_var_name] = val return view_func(request, *args, **kwargs)
def _wrapped_view_func(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: for param in post_params: if param.func_var_name in kwargs: continue if param.argument_type == 'body': try: val = ujson.loads(request.body) except ValueError: raise InvalidJSONError(_("Malformed JSON")) kwargs[param.func_var_name] = val continue elif param.argument_type is not None: # This is a view bug, not a user error, and thus should throw a 500. raise Exception(_("Invalid argument type")) post_var_names = [param.post_var_name] if param.aliases: post_var_names += param.aliases default_assigned = False post_var_name = None # type: Optional[str] query_params = request.GET.copy() query_params.update(request.POST) for req_var in post_var_names: try: val = query_params[req_var] except KeyError: continue if post_var_name is not None: raise RequestConfusingParmsError(post_var_name, req_var) post_var_name = req_var if post_var_name is None: post_var_name = param.post_var_name if param.default is REQ.NotSpecified: raise RequestVariableMissingError(post_var_name) val = param.default default_assigned = True if param.converter is not None and not default_assigned: try: val = param.converter(val) except JsonableError: raise except Exception: raise RequestVariableConversionError(post_var_name, val) # Validators are like converters, but they don't handle JSON parsing; we do. if param.validator is not None and not default_assigned: try: val = ujson.loads(val) except Exception: raise JsonableError( _('Argument "%s" is not valid JSON.') % (post_var_name, )) error = param.validator(post_var_name, val) if error: raise JsonableError(error) # str_validators is like validator, but for direct strings (no JSON parsing). if param.str_validator is not None and not default_assigned: error = param.str_validator(post_var_name, val) if error: raise JsonableError(error) kwargs[param.func_var_name] = val return view_func(request, *args, **kwargs)