Send a tampered response
JSON definition · shared/definitions/relational-storage.v1.json
View on GitHub
{
"title": "Insurance claim",
"elements": [
{
"type": "text",
"name": "q_email",
"valueName": "customer_email",
"dbColumn": "claims.customer_email",
"title": "Email",
"inputType": "email",
"isRequired": true
},
{
"type": "text",
"name": "q_amount",
"valueName": "amount",
"dbColumn": "claims.amount",
"title": "Amount claimed",
"inputType": "number",
"min": 0
},
{
"type": "dropdown",
"name": "incident",
"title": "What happened?",
"choices": [
{
"value": "collision",
"text": "Collision"
},
{
"value": "theft",
"text": "Theft"
},
{
"value": "weather",
"text": "Storm or flood"
}
]
},
{
"type": "comment",
"name": "details",
"title": "Details"
},
{
"type": "boolean",
"name": "priority_handling",
"title": "Priority handling"
}
]
}
Client · shared/client/validate-response.js · sjs:validate-response.request
View on GitHub
// Inspect the submitted payload and the server's validation errors in Requests
async function submit(data) {
const payload = { formId: "claim", data };
const response = await fetch("/api/responses", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload)
});
const report = await response.json();
if (response.status === 400 && Array.isArray(report.errors) && report.errors.length) {
return { rejected: true, errors: report.errors };
}
if (!response.ok) throw new Error(report.error || "Couldn't validate the response. Please try again.");
if (!Number.isInteger(report.id) || report.id < 1) throw new Error("The server didn't confirm a saved response. Please try again.");
setStoredQuery({ id: report.id });
return { id: report.id };
}
Client · shared/client/validate-response.js · sjs:validate-response.client
View on GitHub
// Confirm a save only after the backend accepts the answers and returns a response ID
survey.onComplete.add(async (sender, options) => {
lock(true);
sender.completedHtml = "<h3>Submitting your claim...</h3>";
options.showSaveInProgress();
try {
const result = await submit(sender.data);
if (result.rejected) throw new Error(result.errors.map(describe).join("; "));
sender.completedHtml = `<h3>Your claim has been saved.</h3><p>Response ID: ${result.id}</p>`;
options.showSaveSuccess();
} catch (error) {
sender.completedHtml = "<h3>Your claim hasn't been saved.</h3>";
const message = error instanceof TypeError ? "Couldn't validate the response. Please try again." : error.message;
options.showSaveError(message);
} finally { lock(false); }
});
Server · src/main/java/io/surveyjs/examples/ValidateResponseController.java · sjs:validate-response.server
View on GitHub
// POST /api/responses — ask the SurveyJS service to validate, then store as usual
@PostMapping("/api/responses")
public ResponseEntity<Map<String, Object>> saveValidatedResponse(@RequestBody JsonNode body) {
// A JsonNode, not a DTO: the stored answers keep every key, {} and 1.0 (see Save Responses)
if (!body.path("formId").isString() || !body.path("data").isObject()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Expected { formId, data } with an answers object");
}
String form = jdbc.sql("SELECT json FROM forms WHERE key = ?").param(body.get("formId").asString()).query(String.class).optional()
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Unknown form"));
ServiceAnswer check = surveyjs.post("/response", Map.of("schema", json.readTree(form), "response", body.get("data")), Duration.ofSeconds(10));
JsonNode answer = check.json(); // null when it isn't JSON: fails closed below
if (check.status() == 422 && answer != null && answer.has("errors")) {
if (answer.has("warnings")) { // the stored definition itself has errors
throw surveyjs.unexpected("/response", check, "The stored definition has errors");
}
return ResponseEntity.badRequest().body(Map.of("errors", answer.get("errors"))); // the answers don't fit the definition
}
if (check.status() != 200 || !(answer instanceof ObjectNode valid && valid.isEmpty())) { // fail closed: only exactly {} means valid
throw surveyjs.unexpected("/response", check);
}
int id = storedJson.insertResponse(body.get("formId").asString(), body.get("data")); // stored as it arrived: 1.0 stays 1.0
return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("id", id));
}